<?php

namespace app\admin\controller\kuerp;

use addons\kuerp\model\ExamineRecord;
use addons\kuerp\model\Flows;
use addons\kuerp\model\GoodsSalesInfo;
use addons\kuerp\model\Message;
use addons\kuerp\model\OperationLog;
use addons\kuerp\model\Record;
use addons\kuerp\model\Staff;
use addons\kuerp\model\Collection;
use addons\kuerp\model\Field;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\Goods as GoodsModel;
use app\admin\model\kuerp\Stores;
use app\admin\model\kuerp\StaffMember;
use app\admin\model\kuerp\Customers;
use app\common\controller\Backend;
use \app\admin\model\department\Department as DepartmentModel;
use \app\admin\model\ScoreApply;
use think\Db;
use Exception;
use think\Session;
use think\exception\PDOException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date as PHPExcel_Shared_Date;
use fast\Tree;
/**
 * 销货单
 *
 * @icon fa fa-circle-o
 */
class GoodsSales extends Backend
{
    protected $noNeedRight = ['checkPurchase','getSuppliers','getUnits','getUnit','formatInfo2','getBranch','getTime','getReceivingAddress', 'test','get_goods_sales_info',
        'get_collection','get_goodssalesoperation_log'];
    /**
     * GoodsSales模型对象
     * @var \app\admin\model\kuerp\GoodsSales
     */
    protected $model = null;
    protected $childrenSales = [];
    protected $examineAdmins = [];
    protected $scoreConfig = [];
//    protected $goods_code_caijia = [];  //材价通
//    protected $goods_code_wls = [];  //网络锁

    public function _initialize()
    {
        parent::_initialize();
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set',$setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);

        $this->model = new \app\admin\model\kuerp\GoodsSales;
        $this->view->assign("purchaseTypeList", $this->model->getPurchaseTypeList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("checkStatusList", $this->model->getCheckStatusList());
        $this->view->assign("examineStatusList", $this->model->getExamineStatusList());

        $supplierslist = $this->model->getSuppliersList();
        $this->view->assign("suppliersList", $supplierslist);
        $this->assignconfig("suppliersList", $supplierslist);
        $this->assignconfig("expendTypeList", $this->model->getExpendTypeList());

        $goodslist = (new GoodsModel())->getGoodsList();
        $this->view->assign("goodsList", $goodslist);
        $this->assignconfig("goodsList", $goodslist);

        $this->view->assign("adminList", $this->model->getAdminList());
        $this->view->assign("accountsList", $this->model->getAccountsList());
        $customerwhere = [];
        $adminids = [];
        $this->childrenSales = $this->auth->childrenSales;
        if (!$this->auth->isSuperAdmin()) {
            // if ($this->childrenSales) {
            //     $customerwhere = ['staff_member_id' => ['exp', Db::raw(' in ('.implode(',', $this->childrenSales).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')]];
            // } else {
            //     $customerwhere = ['staff_member_id' => ['exp', Db::raw(' = -1  OR FIND_IN_SET('.$this->auth->id.',collaborator)')]];
            // }
        }
        //系统设置特定审核人员
        $config_site_examine_admins = config('site.examine_admins');
        if (!empty($config_site_examine_admins[$this->auth->id])) {
            $config_examine_admins = explode(',', $config_site_examine_admins[$this->auth->id]);
            $this->examineAdmins = $config_examine_admins;
            //获取对应销售id
            $config_sale_users = (new StaffMember())->getStaffMemberIds($config_examine_admins);
            $this->childrenSales = array_merge($this->childrenSales,$config_sale_users);
        }
        $storesList = (new Stores())->getStoresList(0, $adminids);
        $this->view->assign("storesList", $storesList);
        $this->assignconfig("storesList", $storesList);
        // $searchCustomers = (new Customers())->where($customerwhere)->select();
        $this->view->assign("searchCustomers", []);
        $salelist = (new StaffMember())->getSaleList($this->childrenSales);
        // $this->view->assign("searchSaleList", $salelist);
        $saleLists = [];
        foreach ($salelist as $salelist_k=>$salelist_v){
            $saleLists[] = ['name'=>$salelist_v['name'],'value'=>$salelist_v['id']];
        }
        $this->assignconfig("saleLists", $saleLists);

        $this->view->assign("customers", (new Customers())->getCustomersData($this->childrenSales));
        $this->view->assign("saleList", $salelist);

        $accountsList = $this->model->getAccountsList();
        foreach ($accountsList as $accountsList_k=>$accountsList_v){
            if($accountsList_v['is_default']==1){
                $this->view->assign("accountsDefault", $accountsList_v['id']);
                $this->assignconfig("accountsDefault", $accountsList_v['id']);
            }
        }
        $this->view->assign('is_sale', $this->auth->is_sale);//是否销售
        $stores_id = '';
        if ($this->auth->is_sale) {
            $stores_id = $this->auth->stores_info['id'] ?? '';
        }
        $this->view->assign("stores_id", $stores_id);
        $this->view->assign("buy_type", config('site.buy_type'));
        $this->view->assign("buy_version", config('site.buy_version'));
        $this->view->assign("goodstypelist", config('site.goods_buy_type'));
        $this->assignconfig("stores_id", $stores_id);
        $this->assignconfig('hasExportPermission', $this->auth->check($setData['nowmenu'].'/export') == 1);//是否有导出权限
        //票据
        $this->view->assign("receipt_type", Field::getField('票据', 'contract'));
        //是否需要开启积分申请
        $score_config = \app\common\model\caijiatong\ShoproConfig::getScoreConfig();
        $this->scoreConfig = $score_config;
        $is_enable_score = $score_config['consume_get_score'] ?? 0;
        $this->assignconfig("is_enable_score", $is_enable_score);
//        $this->goods_code_caijia = ['SP002','SP003','SP006','SP060','SP047']; //材价产品
//        $this->goods_code_wls = ['SP005','SP016','SP024']; //网络锁
    }

    public function import()
    {
        if ($this->request->isPost()){
            set_time_limit(0);
            ini_set('memory_limit', '512M');
            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
            $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

            $table = $this->model->getQuery()->getTable();
            $database = \think\Config::get('database.database');
            $fieldArr = [];
            $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
            foreach ($list as $k => $v) {
                if ($importHeadType == 'comment') {
                    $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
                } else {
                    $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
                }
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $row1 = (string)$currentSheet->getCellByColumnAndRow(1, 1)->getValue();
                $titleRow = $row1 == '基础信息' ? 2 : 1;
                $fields = [];
                for ($currentRow = $titleRow; $currentRow <= $titleRow; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $val = str_replace('*','',$val);
                        $fields[] = (string)trim($val);
                    }
                }
                $curcode = '';
                $count = 0;
                for ($currentRow = $titleRow+1; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : trim($val);
                    }
                    $row = array_combine($fields, $values);
                    // $curcode = (new Goods())->getCodes($curcode,11);
                    if ($count == 0) {
                        //获取表数量
                        $purchase_code = $this->model->order('id desc')->value('purchase_code');
                        if (!empty($purchase_code)) {
                            $codearr = explode('-',$purchase_code);
                            $count = $codearr[2];
                        }
                    }
                    $count += 1;
                    $curcode  = 'NBG-'.date('Ymd',strtotime($row['创建时间'])).'-'.$count;
                    
                    $row['单据编号'] = $curcode;
                    $row['单据日期'] = date('Y-m-d',strtotime($row['创建时间']));
                    // if (isset($row['订单标题'])) {
                    //     $row['单据编号'] = $row['订单标题'];
                    //     if (!empty($row['创建时间'])) {
                    //         $row['单据日期'] = date('Y-m-d',strtotime($row['创建时间']));
                    //     } else {
                    //         $title = explode('-',$row['订单标题']);
                    //         $row['单据日期'] = date('Y-m-d',strtotime('20'.$title[1]));
                    //     }
                    // }
                    $row['客户名称'] = !empty($row['对应客户']) ? $row['对应客户'] : ($row['客户名称'] ?? '');
                    $row['销售金额'] = !empty($row['订单总金额']) ? $row['订单总金额'] : ($row['销售金额'] ?? 0);
                    $row['已收款金额'] = !empty($row['已回款金额']) ? $row['已回款金额'] : ($row['已收款金额'] ?? 0);
                    $row['客户联系人'] = !empty($row['联系人姓名']) ? $row['联系人姓名'] : ($row['客户联系人'] ?? '');
                    $row['锁号'] = !empty($row['锁编号']) ? $row['锁编号'] : ($row['锁号'] ?? '');
                    $row['销售员'] = !empty($row['负责人']) ? $row['负责人'] : ($row['销售员'] ?? '');
                    $row['其他返款'] = 0;//!empty($row['其他返款']) ? $row['其他返款'] : 0;
                    $row['创建时间'] = !empty($row['创建时间']) ? strtotime($row['创建时间']) : time();
                    $insert[] = $row;
                }
            } catch (Exception $exception) {
                $this->error($exception->getMessage());
            }
            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            $goods = [];$saler = [];$customers = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(empty($insert_v['单据编号']) && empty($insert_v['客户名称']) && empty($insert_v['产品名称'])){
                    unset($insert[$insert_k]);
                }else{
                    if(!empty($insert_v['客户名称']) && !in_array($insert_v['客户名称'],$customers)){
                        $customers[] = $insert_v['客户名称'];
                    }
                    if(!empty($insert_v['产品名称']) && !in_array($insert_v['产品名称'],$goods)){
                        $goods[] = $insert_v['产品名称'];
                    }
                    if(!empty($insert_v['销售员']) && !in_array($insert_v['销售员'],$saler)){
                        $saler[] = $insert_v['销售员'];
                    }
                }
            }

            $goodslist = Db::name('kuerp_goods')->where(['goods_name'=>['in',$goods]])->column('id,goods_code,serial','goods_name');
            $goodsname = $goodslist ? array_keys($goodslist) : [];
            if(count($goodsname)!=count($goods)){
                foreach ($goods as $goods_k=>$goods_v){
                    if(!in_array($goods_v,$goodsname)){
                        $this->error('产品['.$goods_v.']不存在，导入失败');
                    }
                }
            }
            $customerslist = Db::name('kuerp_customers')->where(['customer_name'=>['in',$customers]])->column('id,staff_member_id','customer_name');
            $customersname = $customerslist ? array_keys($customerslist) : [];
            if(count($customersname)!=count($customers)){
                foreach ($customers as $customers_k=>$customers_v){
                    if(!in_array($customers_v,$customersname)){
                        $this->error('客户['.$customers_v.']不存在，导入失败');
                    }
                }
            }
            //获取联系人
            $customeruserlist = Db::name('kuerp_customers_user')->where(['sid'=>['in',array_column($customerslist, 'id')]])->column('id,sid,first_connect_name');
            $customerusers = [];
            foreach ($customeruserlist as $item) {
                $customerusers[$item['sid']][$item['first_connect_name']] = $item;
            }
            //获取销售员
            // $salerlist = Db::name('kuerp_staff_member')->where(['name'=>['in',$saler]])->column('id,admin_id','name');
            // $salername = $salerlist ? array_keys($salerlist) : [];//Db::name('kuerp_staff_member')->where(['name'=>['in',$saler]])->column('name');
            // if(count($salername)!=count($saler)){
            //     foreach ($saler as $saler_k=>$saler_v){
            //         if(!in_array($saler_v,$salername)){
            //             $this->error('昵称为['.$saler_v.']的销售员不存在，导入失败');
            //         }
            //     }
            // }
            $allsalerlist = Db::name('kuerp_staff_member')->column('name,admin_id','id');
            //获取销售仓库
            $storelist = Db::name('kuerp_stores')->where(['status' => 1, 'deletetime' => null])->column('id,admin_id','name');
            
            //获取单位
            $unitlist = Db::name('kuerp_unit')->where(['type'=>1])->column('id','name');

            $params = [];
            $nowsp = '';
            $codes = [];
            $serialmap = [
                '安' => 'A',//没有锁内码
                '计' => 'J',
                '算' => 'L',
            ];
            foreach ($insert as $insert_k=>$insert_v){
                if (empty($insert_v['单据编号']) && empty($insert_v['产品名称'])) {
                    $this->error('导入失败，单据编号和产品名称不能同时为空');
                }
                if(!empty($insert_v['客户名称'])){
                    $nowsp = $insert_k;
                    
                    if(in_array($insert_v['单据编号'],$codes)){
                        $this->error('导入失败，单据编号'.$insert_v['单据编号'].'重复');
                    }
                    $codes[] = $insert_v['单据编号'];
                    if (empty($customerusers[$customerslist[$insert_v['客户名称']]['id']][$insert_v['客户联系人']])) {
                        $customers_users = !empty($customerusers[$customerslist[$insert_v['客户名称']]['id']]) ? array_values($customerusers[$customerslist[$insert_v['客户名称']]['id']])[0]['id'] : 0;
                    } else {
                        $customers_users = $customerusers[$customerslist[$insert_v['客户名称']]['id']][$insert_v['客户联系人']]['id'];
                    }
                    
                    $params[$insert_k] = [
                        'purchase_code'     =>  $insert_v['单据编号'],
                        'purchase_type'     =>  1,
                        'purchase_time'     =>  strtotime($insert_v['单据日期']),
                        'customers_id'      =>  (int)$customerslist[$insert_v['客户名称']]['id'],//客户
                        'sale_user'         =>  $customerslist[$insert_v['客户名称']]['staff_member_id'] ?? 0,//$salerlist[$insert_v['销售员']]['id'],//销售员
                        'sale_user_name'    =>  $allsalerlist[$customerslist[$insert_v['客户名称']]['staff_member_id']]['name'],//$insert_v['销售员'],//销售员名称
                        'receiving_address' =>  '',
                        'customers_money'   =>  0,

                        'number'            =>  0,
                        'all_money'         =>  (float)$insert_v['销售金额'],

                        'tax_money'         =>  0,//税
                        'money_tax_price'   =>  (float)$insert_v['销售金额'],//价税合计
                        'back_money'        =>  (float)$insert_v['其他返款'],//返款金额

                        'preferential_rate' =>  0,
                        'preferential_money'=>  (float)$insert_v['其他返款'],
                        'real_money'        =>  (float)$insert_v['销售金额'] - (float)$insert_v['其他返款'],
                        'purchase_money'    =>  0,
                        'note'              =>  $insert_v['备注'] ?? $insert_v['锁号'],
                        'buy_type'          =>  $insert_v['购买类型'] ?? '',
                        'buy_version'       =>  $insert_v['版本'] ?? '',
                        'customers_users'   =>  $customers_users,
                        'serials'           =>  $insert_v['锁号'] ?? '',
                        'lock_code'         =>  $insert_v['锁内码'] ?? '',
                        'preparation_id'    =>  $allsalerlist[$customerslist[$insert_v['客户名称']]['staff_member_id']]['admin_id'],//$salerlist[$insert_v['销售员']]['admin_id'],
                        'operation_id'      =>  $allsalerlist[$customerslist[$insert_v['客户名称']]['staff_member_id']]['admin_id'],//$salerlist[$insert_v['销售员']]['admin_id'],

                        'arrears'           =>  0,
                        'all_arrears'       =>  0,

                        'purchase_order_id' =>  0,

                        'pay_status'        =>  (string)($insert_v['销售金额'] == $insert_v['已收款金额'] ? 1 : ($insert_v['已收款金额'] > 0 ? 2 : 0)),
                        'pay_money'         =>  $insert_v['已收款金额'],
                        'account'           =>  0,
                        'cost_data'         =>  null,
                        'examine_status'    =>  1,
                        'createtime'        => $insert_v['创建时间'] ?? time(),
                        'updatetime'        => $insert_v['创建时间'] ?? time(),
                        'goodslist'         => [],
                        'first'             => 0,
                        'serial_code'       => ['serial' => $insert_v['锁号'], 'code' => $insert_v['锁内码'] ?? ''],
                    ];
                }
                if(isset($params[$nowsp]['goodslist']) && (!empty($insert_v['产品名称']))){
                    //商品单位
                    if (!empty($unitlist[$insert_v['产品单位']])) {
                        $goods_unitid = $unitlist[$insert_v['产品单位']];
                    } else {
                        $goods_unitid = Db::name('kuerp_unit')->insertGetId(['name'=>$insert_v['产品单位'],'type'=>1, 'createtime' => time(), 'updatetime' => time()]);
                        $unitlist[$insert_v['产品单位']] = $goods_unitid;
                    }
                    $all_money = (float)$insert_v['产品售价'] * (int)$insert_v['产品数量'] - (float)($insert_v['产品返款金额'] ?? 0);
                    //单个商品金额大于订单金额
                    if ($all_money > $params[$nowsp]['all_money']) {
                        if($insert_v['产品售价'] == $params[$nowsp]['all_money']) {
                            $all_money = $insert_v['产品售价'];
                            $insert_v['产品售价'] = $all_money / (int)$insert_v['产品数量'];
                        } else {
                            //判断该订单有几款产品
                            //只有一款
                            if (count($params[$nowsp]['goodslist']) == 0 && (empty($insert[$insert_k + 1]) || (empty($insert[$insert_k + 1]['单据编号']) && !empty($insert_v['产品名称'])))) {
                                $all_money = $params[$nowsp]['all_money'];
                                $insert_v['产品售价'] = $all_money / (int)$insert_v['产品数量'];
                            } else {
                                
                            }
                        }
                    }
                    
                    $params[$nowsp]['number'] += (int)$insert_v['产品数量'];
                    $serial_code = $params[$nowsp]['serial_code'];
                    $serial = $serial_code['serial'] ? explode("\n", str_replace(["\r\n", ' ', '、'], ["\n","\n","\n"], $serial_code['serial'])) : [];
                    $code = $serial_code['code'] ? explode("\n", str_replace(["\r\n", ' ', '、'], ["\n","\n","\n"], $serial_code['code'])) : [];
                    $period = [];
                    //判断该订单是否只有一个商品
                    if ($serial) {
                        if (count($serial) > 1) {
                            //截取商品第一个字
                            $firstname = mb_substr($insert_v['产品名称'], 0, 1);
                            if(!empty($serialmap[$firstname])) {
                                $mapcode = $serialmap[$firstname];
                                //查找$serial 里面带有$serialmap[$firstname]字符则为该商品锁号
                                $curserial = array_filter($serial, function($item) use($mapcode) {
                                    return strpos($item, $mapcode) !== false;
                                });
                                foreach ($curserial as $curserial_k => $curserial_v) {
                                    $period[] = [
                                        'serial' => $curserial_v,
                                        'remark' => $code[$curserial_k] ?? '',
                                    ];
                                }
                            } 
                        } else {
                            if (count($params[$nowsp]['goodslist']) == 0){
                                $period[] = [
                                    'serial' => $serial_code['serial'],
                                    'remark' => $serial_code['code'],
                                ];
                            }
                        }
                    }
                    
                    $params[$nowsp]['goodslist'][] = [
                        'purchase_code'     =>  $params[$nowsp]['purchase_code'],
                        'purchase_type'     =>  1,
                        'purchase_time'     =>  $params[$nowsp]['purchase_time'],
                        'customers_id'      =>  $params[$nowsp]['customers_id'],//客户
                        'sale_user'         =>  $params[$nowsp]['sale_user'],//销售员
                        'sale_user_name'    =>  $params[$nowsp]['sale_user_name'],//销售员名称
                        'receiving_address' =>  '',

                        'goods_code'        =>  $goodslist[$insert_v['产品名称']]['goods_code'],//商品信息
                        'goods_note'        =>  $insert_v['产品备注'],
                        'goods_unit'        =>  (float)$goods_unitid,

                        'stores_id'         =>  $storelist['总仓库']['id'],//$storelist[$params[$nowsp]['销售员']]['id'] ?? $storelist['总仓库']['id'],
                        'allow_stock'       =>  0,
                        'order_info_id'     =>  0,
                        'number'            =>  (int)$insert_v['产品数量'],
                        'default_unit'      =>  (float)$goods_unitid,
                        'basic_nmber'       =>  (int)$insert_v['产品数量'],
                        'unit_price'        =>  (float)$insert_v['产品售价'],
                        'cost_price'        =>  0,
                        'discount'          =>  0,
                        'dis_money'         =>  0,
                        'back_money'        =>  (float)($insert_v['产品返款金额'] ?? 0),
                        'all_money'         =>  (float)$all_money,
                        'remark'            =>  '',

                        'goods_attr'        =>  (float)0,
                        'tax_included'      =>  (float)$insert_v['产品售价'],
                        'tax_rate'          =>  0,
                        'tax_money'         =>  0,
                        'money_tax_price'   =>  (float)$all_money,

                        'batch_id'          => 0,
                        'batch_name'        => '',
                        'manufacture'       => 0,
                        'guarantee'         => 0,
                        'validity'          => 0,

                        'preferential_rate' =>  0,
                        'preferential_money'=>  0,
                        'real_money'        =>  (float)$params[$nowsp]['all_money'],
                        'purchase_money'    =>  0,
                        'preparation_id'    =>  $params[$nowsp]['preparation_id'],
                        'operation_id'      =>  $params[$nowsp]['operation_id'],

                        'pay_status'        =>  (string)($params[$nowsp]['all_money'] == $params[$nowsp]['pay_money'] ? 1 : ($params[$nowsp]['pay_money'] > 0 ? 2 : 0)),
                        'pay_money'         =>  $params[$nowsp]['pay_money'],
                        'account'           =>  0,

                        'purchase_order_id' =>  '',

                        'createtime'        => $params[$nowsp]['createtime'],
                        'updatetime'        => $params[$nowsp]['updatetime'],
                        'period'            => $period ? serialize($period) : '',
                    ];
                }
            }
            // var_dump($params);die;
            $editstatus = isset($_POST['editstatus'])?$_POST['editstatus']:1;
            $edit_arr = [];
            if($editstatus==0){
                $code_s =  $this->model->where(['purchase_code'=>['in',$codes]])->value('purchase_code');
                if(!empty($code_s)){
                    $this->error('导入失败，单据编号['.$code_s.']已存在');
                }
            }else{
                $code_list = $this->model->where(['purchase_code'=>['in',$codes]])->column('id','purchase_code');
                foreach ($params as $params_k=>$params_v){
                    if(isset($code_list[$params_v['purchase_code']])){
                        $params_v['id'] = $code_list[$params_v['purchase_code']];
                        $edit_arr[] = $params_v;
                        unset($params[$params_k]);
                    }
                }
            }
            
            Db::startTrans();
            try {
                if(!empty($params)){
                    foreach ($params as $params_k=>$params_v){
                        $goodsarr = $params_v['goodslist'];
                        unset($params_v['goodslist']);
                        unset($params_v['first']);
                        unset($params_v['serial_code']);
                        $result = Db::name('kuerp_goods_sales')->insertGetId($params_v);

                        if(!empty($goodsarr)){
                            Db::name('kuerp_goods_sales_info')->insertAll($goodsarr);
                            foreach ($goodsarr as $info_list_k=>$info_list_v){
                                if(isset($info_list_v['id'])){
                                    unset($goodsarr[$info_list_k]['id']);
                                }
                            }
                            Db::name('kuerp_goods_sales_summary')->insertAll($goodsarr);
                        }
                        
                    }
                }
                if(!empty($edit_arr)){
                    foreach ($edit_arr as $edit_arr_k=>$edit_arr_v){

                        $goodsarr = $edit_arr_v['goodslist'];unset($edit_arr_v['goodslist']);unset($edit_arr_v['first']);unset($edit_arr_v['serial_code']);
                        $id = $edit_arr_v['id'];
                        unset($edit_arr_v['createtime']);unset($edit_arr_v['id']);
                        $result = $this->model->where(['id'=>$id])->update($edit_arr_v);
                        Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$edit_arr_v['purchase_code']])->delete();
                        if(!empty($goodsarr)){
                            Db::name('kuerp_goods_sales_info')->insertAll($goodsarr);
                        }
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success(['update'=>sizeof($edit_arr),'add'=>sizeof($params)]);
        }
        $this->assign('time', time());
        return $this->view->fetch();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            $ruleWhere = [];
            if (!$this->auth->isSuperAdmin()) {
                if ($this->auth->is_sale) {
                    // $ruleWhere = ['sale_user' => $this->auth->staff_member_id];
                    $ruleWhere['sale_user'] = ['exp', Db::raw(' ='.$this->auth->staff_member_id.'  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                }
                $sale_users = $this->childrenSales;
                if ($sale_users) {
                    $ruleWhere['sale_user'] = ['exp', Db::raw(' in ('.implode(',', $sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                } else {
                    $ruleWhere['sale_user'] = ['exp', Db::raw(' = -1  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
                }
            }
            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            if (isset($filter['examine_status'])) {
                // 自定义处理
                $examine_status = $filter['examine_status'];
                // 处理完可以去掉也可以覆盖重构
                unset($filter['examine_status'],$op['examine_status']);
            }
            $examine_status = isset($examine_status) ? (int)$examine_status : null;
            if ($examine_status == 1) {
                $ruleWhere['examine_status'] = '1';
            }else if ($examine_status === 0) {
                $ruleWhere['examine_status'] = '0';
                $ruleWhere['examine_index'] = 0;
                $ruleWhere['examine_adminids'] = '';
            } else if ($examine_status == 2) {
                $ruleWhere['examine_status'] = 2;
            } else if ($examine_status == 3) {//审核中
                $ruleWhere['examine_status'] = '0';
                $ruleWhere['examine_index'] = ['exp', Db::raw('>0 OR (examine_index = 0 && examine_adminids != "")')];
            }    
            if (isset($filter['department_id'])) {
                // 自定义处理
                $department_id = $filter['department_id'];
                if($department_id) {
                    $departmentids = DepartmentModel::getChildrenIds($department_id, true);
                    $adminids = Admin::getDepartmentAdminIds($departmentids);
                    $sales = (new StaffMember())->getStaffMemberIds($adminids);
                    $ruleWhere['sale_user'] = ['in', $sales];
                }
                // 处理完可以去掉也可以覆盖重构
                unset($filter['department_id'],$op['department_id']);
            }    
            if (isset($filter['serials'])) {
                // 自定义处理
                $serials = $filter['serials'];
                $ruleWhere['serials|lock_code|goods_sales.note'] = ['like', '%'.$serials.'%'];
                // 处理完可以去掉也可以覆盖重构
                unset($filter['serials'],$op['serials']);
            } 
            if (!empty(input('purchase_time'))) {
                $purchase_time = str_replace(' - ', ',', input('purchase_time'));
                $arr = array_slice(explode(',', $purchase_time), 0, 2);
                $ruleWhere['goods_sales.purchase_time'] = ['between time', $arr];
            }
           
            $this->request->get(['filter'=>json_encode($filter,true)]);
            $this->request->get(['op'=>json_encode($op,true)]);
            $this->request->get(['sort'=>$this->request->get('sort') ?? 'purchase_time']);
            $this->request->get(['order'=>$this->request->get('order') ?? 'desc']);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($sort == 'goods_sales.nopay_money') {
                $sort = 'nopay_money';
            }
            // $sort = 'purchase_time';$order='DESC';
            $list = $this->model
                // ->with(['customers','preparation','examine'])
                ->with(['customers'])
                ->where($where)
                ->where($ruleWhere)
                ->field('(goods_sales.real_money - goods_sales.pay_money) as nopay_money')
                ->order($sort, $order)
                ->order('goods_sales.id', 'DESC')
                ->paginate($limit);
            // echo $this->model->getLastSql();
            foreach ($list as $row) {
                $row->getRelation('customers')->visible(['customer_name']);
                // $row->getRelation('preparation')->visible(['username', 'nickname']);
                // $row->getRelation('examine')->visible(['username', 'nickname']);
            }
            $counts = [];
            $sums = $this->model
            ->with(['customers'])
            ->where($where)
            ->where($ruleWhere)
            ->field('sum(money_tax_price) as money_tax_price,sum(pay_money) as pay_money,sum(back_money) as back_money,sum(real_money) as real_money,sum(goods_number) as goods_number')
            ->find();
            // echo $this->model->getLastSql();
            $counts['money_tax_price'] = $sums['money_tax_price'] ? round($sums['money_tax_price'], 2) : 0;
            $counts['pay_money'] = $sums['pay_money'] ? round($sums['pay_money'], 2) : 0;
            $counts['back_money'] = $sums['back_money'] ?round($sums['back_money'], 2) :  0;
            $counts['real_money'] = $sums['real_money'] ?round($sums['real_money'], 2) :  0;
            $counts['goods_money'] = round($counts['money_tax_price'] + $counts['back_money'], 2);
            $counts['goods_number'] = round($sums['goods_number'], 2);
            $adminList = [];
            $examine_index = 0;//判断流程中是否有当前用户审核
            $last_examine_indexs = [];
            $first_children_ids = [];
            $enablePurchaseCodes = [];
            if ($list) {
                $adminids = array_column($list->items(), 'preparation_id');
                $adminids1 = array_column($list->items(), 'examine_id');
                $adminids = array_unique(array_merge($adminids, $adminids1));
                $adminList = \app\admin\model\Admin::where(['id' => ['in', $adminids]])->column('username,nickname', 'id');
                //获取审批流程
                $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
                if (!empty($flows)){
                    $flows['flow_items'] = json_decode($flows['flow_items'], true);
                    //判断流程中是否有当前用户审核
                    foreach ($flows['flow_items'] as $key => $value) {
                        if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                            $examine_index = $key + 1;
                            $last_examine_indexs[] = $key;
                            // break;
                        }
                    }
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        //获取直属下级
                        $department_ids = Admin::getPrincipalIds($this->auth->id);
                        if ($department_ids) {
                            $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                            $children_ids = array_unique(array_merge($children_ids, $this->examineAdmins));
                            if ($children_ids) {
                                $first_children_ids = (new StaffMember())->getStaffMemberIds($children_ids);
                            }
                        }
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                }
                //判断是否可申请积分 根据订单商品 
                $payedOrderSales = array_filter($list->items(), function ($item) {
                    return $item['nopay_money'] == 0;
                });
                $purchase_codes = array_column($payedOrderSales, 'purchase_code');
                $enablePurchaseCodes = GoodsSalesInfo::where(['purchase_code' => ['in', $purchase_codes], 'goods_code' => ['in',array_merge($this->goods_code_caijia,$this->goods_code_xunjia)]])->column('purchase_code');
            }
            foreach ($list as $list_k=>$list_v){
                // if(isset($list_v['print_num']) && empty($list_v['print_num'])){
                //     $list[$list_k]['print_num'] = 0;
                // }
                // $purchase_id = Db::name('kuerp_goods_saleexc')->where(['purchase_id'=>$list_v['id']])->column('exchange_id');
                // $purchase = Db::name('kuerp_goods_sales_exchange')->where(['id'=>['in',$purchase_id]])->column('purchase_code');
                // $list[$list_k]['returns_order_id'] = implode(',',$purchase);
                $list[$list_k]['preparation'] = $adminList[$list_v['preparation_id']] ?? '';
                $list[$list_k]['examine'] = $adminList[$list_v['examine_id']] ?? '';
                //审核状态
                $list[$list_k]['examine_status_texts'] = $list[$list_k]['examine_status_text'];
                if ($list_v['examine_status'] == 0 && ($list_v['examine_index'] > 0 || ($list_v['examine_index'] == 0 && $list_v['examine_adminids'] != ''))) {
                    $list[$list_k]['examine_status_texts'] = '审核中';
                }
                //是否可以审核
                $list[$list_k]['examine_enable'] = false;
                if ($list_v['examine_status'] == 0 && $examine_index > 0) {
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            if (($list_v['examine_index'] == 0 && in_array($list_v['sale_user'], $first_children_ids)) || (in_array($list_v['examine_index'], $last_examine_indexs) && in_array($list_v['sale_user'], $this->childrenSales))) {
                                $list[$list_k]['examine_enable'] = true;
                            }
                        } else {
                            $list[$list_k]['examine_enable'] = true;
                        }
                    } else {
                        if (in_array($list_v['examine_index'], $last_examine_indexs)) {
                            $list[$list_k]['examine_enable'] = true;
                        }
                    }
                }
                $list[$list_k]['enable_apply_score'] = $list_v['real_money'] == $list_v['pay_money'] && in_array($list_v['purchase_code'], $enablePurchaseCodes) ? 1 : 0;
            }

            $result = array("total" => $list->total(), "rows" => $list->items(), 'counts' => $counts);

            return json($result);
        }
        $date_type = [
            ['name' => '今日', 'value' => [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')]],
            ['name' => '昨日', 'value' => [date('Y-m-d 00:00:00', strtotime('-1 day')), date('Y-m-d 23:59:59', strtotime('-1 day'))]],
            ['name' => '本周', 'value' => [date('Y-m-d 00:00:00', strtotime('this week Monday')), date('Y-m-d 23:59:59')]],
            ['name' => '上周', 'value' => [date('Y-m-d 00:00:00', strtotime('last week Monday')), date('Y-m-d 23:59:59', strtotime('last week Sunday'))]],
            ['name' => '本月', 'value' => [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')]],
            ['name' => '上月', 'value' => [date('Y-m-01 00:00:00', strtotime('first day of last month')), date('Y-m-t 23:59:59', strtotime('first day of last month'))]],
            ['name' => '今年', 'value' => [date('Y-01-01 00:00:00'), date('Y-12-31 23:59:59')]],
            ['name' => '去年', 'value' => [date('Y-01-01 00:00:00', strtotime('-1 year')), date('Y-12-31 23:59:59', strtotime('-1 year'))]],
        ];
        $this->view->assign('date_type',$date_type);
        $this->assignconfig('date_type',$date_type);
        // $tree = Tree::instance();
        // $deplist = Admin::getAllDepartmentsArray($this->auth->id,($this->auth->isSuperAdmin()||$this->auth->data_scope)?true:false);
        // $tree->init($deplist, 'parent_id');
        // dump($tree->getTreeArray(0));
        // $departmentList = $tree->getTreeList($deplist, 'name');
        $orgindepartmentList = Admin::getAllDepartmentsTreeArray($this->auth->id, $this->auth->isSuperAdmin()||$this->auth->data_scope);
        $departmentList = [];
        foreach ($orgindepartmentList as $key => $value) {
            $departmentList[] = [
                'id' => $key,
                'name' => $value
            ];
        }
        $this->view->assign("departmentList", $departmentList);
        return $this->view->fetch();
    }

    /**
     * 导出信息
     */
    public function export()
    {
        $param = $this->request->param();
        if (isset($param['user_path'])) {
            if (file_exists($_SERVER['DOCUMENT_ROOT'].$param['user_path'])) {
                unlink($_SERVER['DOCUMENT_ROOT'].$param['user_path']); // 删除文件
            }
            exit();
        }
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $isall = input('isall');
        $ruleWhere = [];
        if($isall != 3 && empty($ids)){
            $this->error(__('请选择要导出的数据'));
        }
        //导出其中几条
        if (isset($ids) ) {
            $ruleWhere['goods_sales.id'] = array('in', $ids);
        }
        //导出全部
        if (isset($isall)) {
            if ($isall == 3) {
                unset($ruleWhere['goods_sales.id']);
            }
        }


        if (!$this->auth->isSuperAdmin()) {
            if ($this->auth->is_sale) {
                // $ruleWhere = ['sale_user' => $this->auth->staff_member_id];
                $ruleWhere['goods_sales.sale_user'] = ['exp', Db::raw(' ='.$this->auth->staff_member_id.'  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
            }
            //部门经理查看部门成员 上级部门能查看下级部门
            // $adminids = (new Admin())->getChildrenAdminIds($this->auth->id, true);
            //转为职员id
            $sale_users = $this->childrenSales;//$adminids ?(new StaffMember())->getStaffMemberIds($adminids) : [];
            if ($sale_users) {
                $ruleWhere['goods_sales.sale_user'] = ['exp', Db::raw(' in ('.implode(',', $sale_users).')  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
            } else {
                $ruleWhere['goods_sales.sale_user'] = ['exp', Db::raw(' = -1  OR FIND_IN_SET('.$this->auth->id.',collaborator)')];
            }
        }
        $filter = json_decode($this->request->get("filter", ''), true);
        $op = json_decode($this->request->get("op", '','trim'), true);
        if (isset($filter['examine_status'])) {
            // 自定义处理
            $examine_status = $filter['examine_status'];
            // 处理完可以去掉也可以覆盖重构
            unset($filter['examine_status'],$op['examine_status']);
        }
        $examine_status = isset($examine_status) ? (int)$examine_status : null;
        if ($examine_status == 1) {
            $ruleWhere['goods_sales.examine_status'] = '1';
        }else if ($examine_status === 0) {
            $ruleWhere['goods_sales.examine_status'] = '0';
            $ruleWhere['goods_sales.examine_index'] = 0;
            $ruleWhere['goods_sales.examine_adminids'] = '';
        } else if ($examine_status == 2) {
            $ruleWhere['goods_sales.examine_status'] = 2;
        } else if ($examine_status == 3) {//审核中
            $ruleWhere['goods_sales.examine_status'] = '0';
            $ruleWhere['goods_sales.examine_index'] = ['exp', Db::raw('>0 OR (examine_index = 0 && examine_adminids != "")')];
        }
        if (isset($filter['department_id'])) {
            // 自定义处理
            $department_id = $filter['department_id'];
            if($department_id) {
                $departmentids = DepartmentModel::getChildrenIds($department_id, true);
                $adminids = Admin::getDepartmentAdminIds($departmentids);
                $sales = (new StaffMember())->getStaffMemberIds($adminids);
                $ruleWhere['goods_sales.sale_user'] = ['in', $sales];
            }
            // 处理完可以去掉也可以覆盖重构
            unset($filter['department_id'],$op['department_id']);
        }
        if (isset($filter['serials'])) {
            // 自定义处理
            $serials = $filter['serials'];
            $ruleWhere['serials|lock_code'] = ['like', '%'.$serials.'%'];
            // 处理完可以去掉也可以覆盖重构
            unset($filter['serials'],$op['serials']);
        }

        $this->request->get(['filter'=>json_encode($filter,true)]);
        $this->request->get(['op'=>json_encode($op,true)]);

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $sort = 'purchase_time';$order='DESC';

        $list = $this->model
            ->with(['customers','preparation','examine','goodssalesinfo'])
            ->where($where)
            ->where($ruleWhere)
            ->order($sort, $order)
            ->order('purchase_code', 'DESC')
            ->field('(goods_sales.real_money - goods_sales.pay_money) as nopay_money')
            ->select();

        foreach ($list as $row) {
            $row->getRelation('customers')->visible(['customer_name','connet_name','customer_mobile']);
            $row->getRelation('preparation')->visible(['username', 'nickname']);
            $row->getRelation('examine')->visible(['username', 'nickname']);
            $row->getRelation('goodssalesinfo')->visible(['goods_code','goods_type','number','unit_price','back_money','all_money','remark','period','start_date', 'end_date', 'goods_number']);
        }

        $list = collection($list)->toArray();
        if (!$list) {
            $this->error('无导出数据');
        }

        $goods_code = array_map(function($item) {
            return $item['goodssalesinfo']['goods_code'];
        }, $list);

        $good = Db::name('kuerp_goods')->alias('a')
            ->join('kuerp_unit b','a.unit_id=b.id','left')
            ->where('a.goods_code','in',$goods_code)
            ->column('a.goods_name,b.name as unit_name','a.goods_code');

        $title = [
            '单据日期',
            '单据编号',
            '销售员',
            '客户名称',
            '产品总金额',
            '销售金额',
            '返款金额',
            '已收款金额',
            '未回款金额',
            '锁编码',
            '锁内码',
            '购买类型',
            '购买版本',
            '票据',
            '订单备注',
            '创建时间',
            '联系人',
            '联系人手机',
            '商品名称',
            '商品编号',
            '商品数量',
            '商品单位',
            '购买类型',
            '销售单价',
            '返款金额',
            '销售金额',
            '锁号',
            '时间期限',
            '询价条数',
            '商品备注',
        ];

        $orderinfo = [];
        foreach ($list as $k => $v) {
            $serial = '';
            if (!empty($v['goodssalesinfo']['period'])) {
                $period = unserialize($v['goodssalesinfo']['period']);
                foreach ($period as $k1=>$v1) {
                    $serial .= $v1['serial'].'-'.$v1['remark'].',';
                }
                $serial = rtrim($serial, ',');
            }
            $field1 = array(
                date('Y-m-d',$v['purchase_time']),
                $v['purchase_code'],
                $v['sale_user_name'] ?? '',
                $v['customers']['customer_name'],
                round(($v['money_tax_price'] + $v['back_money']) * 100) / 100,
                $v['all_money'],
                $v['back_money'] ?? 0,
                $v['pay_money'] ?? 0,
                $v['nopay_money'] ?? 0,
                $v['serials'],
                $v['lock_code'],
                $v['buy_type'] ?? '',
                $v['buy_version'] ?? '',
                $v['receipt'],
                $v['note'] ?? '',
                date('Y-m-d H:i:s',$v['createtime']),
                $v['customers']['connet_name'] ?? '',
                $v['customers']['customer_mobile'] ?? '',
            );

            $field2 = array(
                $good[$v['goodssalesinfo']['goods_code']]['goods_name'] ?? '',
                $good[$v['goodssalesinfo']['goods_code']]['goods_code'] ?? '',
                $v['goodssalesinfo']['number'] ?? 0,
                $good[$v['goodssalesinfo']['goods_code']]['unit_name'] ?? '',
                $v['goodssalesinfo']['goods_type'] ?? '',
                $v['goodssalesinfo']['unit_price'] ?? 0,
                $v['goodssalesinfo']['back_money'] ?? 0,
                $v['goodssalesinfo']['all_money'] ?? 0,
                $serial,
                !empty($v['goodssalesinfo']['start_date']) && !empty($v['goodssalesinfo']['end_date']) ? ($v['goodssalesinfo']['start_date'].' - '.$v['goodssalesinfo']['end_date']) : '',
                $v['goodssalesinfo']['goods_number'],
                $v['goodssalesinfo']['remark'] ?? '',
            );

            if(isset($orderinfo[$v['purchase_code']])){
                $field1 = array_fill(0, count($field1), '');
            }
            $field = array_merge($field1, $field2);
            $orderinfo[$v['purchase_code']] =  $v['purchase_code'];
            $data[] = $field;
        }

        $file = export_excel($title, $data, '订单');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }

    /**
     * 合同详情
     */
    public function detail($ids = null) {
        $row = $this->model->where(['goods_sales.id' => $ids])->with([
            'customers',
            'staffmember',
        ])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $row=$row->toArray();
        $row['ratios'] = [];
        if ($row['ratios']) {
            foreach ($row['ratios'] as $k => $v) {
                $v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
                $v['money'] = $row['money'] * ($v['ratio'] / 100);
                $row['ratios'][$k] = $v;
            }
        }
        $row['repayment_money'] = $row['pay_money']; //Receivables::where(['contract_id'=>$ids])->sum('money'); //已回款
        $row['no_money'] = $row['real_money'] -$row['pay_money'];
        if($row['no_money'] <= 0){
            $row['no_money'] = 0;
        }

        $row['purchase_time'] = date('Y-m-d', $row['purchase_time']);
        //锁编码
        $row['serials'] = $row['serials'] ? str_replace(['，', '/', '、', ' '], ',', $row['serials']) : '';
        $row['lock_code'] = $row['lock_code'] ? str_replace(['，', '/', '、', ' '], ',', $row['lock_code']) : '';
        $serials = $row['serials'] ? explode(',', $row['serials']) : [];
        $lock_code = explode(',', $row['lock_code']);
        $serial_data = [];
        if ($serials) {
            for ($i = 0; $i < count($serials); $i++) { 
                $serial_data[] = [
                    'serial' => $serials[$i],
                    'lock_code' => $lock_code[$i] ?? '',
                ];
            }
        }
        $row['serial_data'] = $serial_data;
        //获取审核信息
        $logWhere = [
            'relation_type' => 'goods_sale',
            'relation_id' => $ids,
        ];
        $logList = Db::name('examine_log')->where($logWhere)->order('id desc')->select();
        if (!empty($logList)) {
            $admin_ids = array_column($logList,'admin_id');
            $admin_data = Db::name('admin')->where(['id'=>['in',$admin_ids]])->column('nickname,username,avatar','id');
            foreach ($logList as $log_k=>$log_v) {
                $logList[$log_k]['admin_name'] = $admin_data[$log_v['admin_id']]['nickname'] ?? $admin_data[$log_v['admin_id']]['username'] ?? '';
                $logList[$log_k]['admin_avatar'] = $admin_data[$log_v['admin_id']]['avatar'] ?? '';
                $logList[$log_k]['createtime'] = date('Y/m/d H:i', $log_v['createtime']);
            }
        }

        $this->assign('log_list',$logList);
        // $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::CONTRACT_TYPE,$ids));
        // $this->assign('flow',Flows::getstepdetail(Flows::GOODSSALE_STATUS, $ids));
        //跟进记录
        $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
        //操作记录
        $log=OperationLog::getList(OperationLog::CONTRACT_TYPE, $ids);
        $examine_index = 0;//判断流程中是否有当前用户审核
        $last_examine_indexs = [];
        $first_children_ids = [];
        //获取审批流程
        $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
        if (!empty($flows)){
            $flows['flow_items'] = json_decode($flows['flow_items'], true);
            //判断流程中是否有当前用户审核
            foreach ($flows['flow_items'] as $key => $value) {
                if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                    $examine_index = $key + 1;
                    $last_examine_indexs[] = $key;
                    // break;
                }
            }
            //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
            $search_index = array_search(0, $last_examine_indexs);
            if(count($last_examine_indexs) > 1 && $search_index !== false) {
                //获取直属下级
                $department_ids = Admin::getPrincipalIds($this->auth->id);
                if ($department_ids) {
                    $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                    $children_ids = array_unique(array_merge($children_ids, $this->examineAdmins));
                    if ($children_ids) {
                        $first_children_ids = (new StaffMember())->getStaffMemberIds($children_ids);
                    }
                }
                $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
            }
        }
        //是否可以审核
        $row['examine_enable'] = false;
        if ($row['examine_status'] == 0 && $examine_index > 0) {
            if (!empty($first_children_ids)) {
                if ($last_examine_indexs) {
                    if (($row['examine_index'] == 0 && in_array($row['sale_user'], $first_children_ids)) || (in_array($row['examine_index'], $last_examine_indexs) && in_array($row['sale_user'], $this->childrenSales))) {
                        $row['examine_enable'] = true;
                    }
                } else {
                    $row['examine_enable'] = true;
                }
            } else {
                if (in_array($row['examine_index'], $last_examine_indexs)) {
                    $row['examine_enable'] = true;
                }
            }
        }
        if ($row['examine_status'] == 0 && ($row['examine_index'] > 0 || ($row['examine_index'] == 0 && $row['examine_adminids'] != ''))) {
            $row['examine_status_texts'] = '审核中';
        }
        $enablePurchaseCodes = GoodsSalesInfo::where(['purchase_code' => $row['purchase_code'], 'goods_code' => ['in',array_merge($this->goods_code_caijia,$this->goods_code_xunjia)]])->find();
        $is_enable_score = $this->scoreConfig['consume_get_score'] ?? 0;
        $row['enable_apply_score'] = $row['real_money'] == $row['pay_money'] && $enablePurchaseCodes && $is_enable_score ? 1 : 0;
        // dump($row);
        $this->assign('operation_log',$log);
        $this->assign('row', $row);
        $this->assign('ids', $ids);

        $this->assignconfig("idinfo", ['id' => $ids,'purchase_code'=>$row['purchase_code']]);

        //标记通知已读
        Message::setRead(['in', [Message::CONTRACT_TYPE, Message::GOODSSALES_TYPE]], $ids, $this->auth->id);
        return $this->view->fetch();
    }

    public function get_goods_sales_info()
    {
        $purchase_code = $this->request->param("purchase_code");
        //获取商品信息
        $goods=GoodsSalesInfo::where(['purchase_code'=>$purchase_code])->with(['goods'])->select();
        foreach ($goods as $row) {
            $row->getRelation('goods')->visible(['goods_name', 'goods_image','id']);
        }
        $list = [];
        if ($goods) {
            $unitids = array_unique(array_column($goods, 'goods_unit'));
            $stores_id = array_unique(array_column($goods, 'stores_id'));
            $goodsunits = Db::name('kuerp_unit')->where('id','in',$unitids)->column('name','id');
            $goodstores_id = Db::name('kuerp_stores')->where('id','in',$stores_id)->column('name','id');
        }
        $default_img = config('site.default_goods_img');
        foreach ($goods as $k=>$v) {
            $list[$k]['id']=$v['id'];
            $list[$k]['number']=$v['number'];
            $list[$k]['goods_id']=$v['goods']['id'];
            $list[$k]['goods_code']=$v['goods_code'];
            $list[$k]['goods_name']=$v['goods']['goods_name'];
            $list[$k]['img']=cdnurl($v['goods']['goods_image'] != '' ? $v['goods']['goods_image'] : $default_img, true);
            $list[$k]['goods_unit']=$goodsunits[$v['goods_unit']];
            $list[$k]['stores_name']=$goodstores_id[$v['stores_id']];
            $list[$k]['unit_id']=$v['goods_unit'];
            $list[$k]['price']=$v['unit_price'];
            $list[$k]['back_money']=$v['back_money'];
            $list[$k]['all_money']=$v['all_money'];
            $list[$k]['serial']='';
            $list[$k]['goods_type']=$v['goods_type'];
            $list[$k]['remark']=$v['remark'];
            $list[$k]['period']= $v['period'] ? unserialize($v['period']) : '';
            if (!empty($v['period'])) {
                $period = unserialize($v['period']);
                foreach ($period as $k1=>$v1) {
                    $list[$k]['serial'] .= $v1['serial'].'-'.$v1['remark'].',';
                }
                $list[$k]['serial'] = rtrim($list[$k]['serial'], ',');
            }
            $list[$k]['date_range']=!empty($v['start_date']) && !empty($v['end_date']) ? ($v['start_date'].' - '.$v['end_date']) : '';;
            $list[$k]['year_number']=$v['year_number'];
            $list[$k]['goods_number']=$v['goods_number'];
        }
        $result = array("total" => count($list), "rows" => $list);

        return json($result);
    }

    public function get_collection()
    {
        $purchase_code = $this->request->param("purchase_code");
        $list = Collection::with(['admin','staffmember','collectionsale'])->where(['collectionsale.purchase_number'=>$purchase_code])->select();

        foreach ($list as $row) {
            $row->getRelation('admin')->visible(['username', 'nickname']);
            $row->getRelation('staffmember')->visible(['name']);
        }

        $lists = [];
        $moneys = 0;$write_off = 0;
        $customers_list = [];
        $admin_list = [];
        if ($list) {
            $customers_list = Db::name('kuerp_customers')->where(['id'=>['in', array_column($list, 'customers_id')]])->column('customer_name', 'id');
            $admin_list = Db::name('admin')->where(['id'=>['in', array_column($list, 'examine_id')]])->column('username,nickname', 'id');
        }
        foreach ($list as $list_k=>$list_v){
            if(isset($list_v['print_num']) && empty($list_v['print_num'])){
                $list_v['print_num'] = 0;
            }
            $customers = $customers_list[$list_v['customers_id']] ?? '';//Db::name('kuerp_customers')->where(['id'=>$list_v['customers_id']])->value('customer_name');
            $staff_member = $list_v['staffmember']['name'];//Db::name('kuerp_staff_member')->where(['id'=>$list_v['staff_member_id']])->value('name');
            $preparation = $list_v['admin']['nickname'];//Db::name('admin')->where(['id'=>$list_v['preparation_id']])->value('username');
            $examine =  $admin_list[$list_v['examine_id']]['nickname'] ?? '';//Db::name('admin')->where(['id'=>$list_v['examine_id']])->value('username');

            $account = Db::name('kuerp_collection_account')->alias('co')
                ->join('kuerp_accounts a','a.id=co.accounts_id')
                ->join('kuerp_settlementtype s','s.id=co.settlementtype','left')
                ->where((new Goods())->setWhere(['co.collection_id'=>$list_v['id']]))
                ->field('co.money,a.account_name,s.name,co.number,co.remark')
                ->select();
            foreach ($account as $account_k=>$account_v){
                $lists[] = [
                    'id'            => $list_v['id'],
                    'purchase_code' => $list_v['purchase_code'],
                    'purchase_time' => date('Y-m-d',$list_v['purchase_time']),
                    'customers_id'  => $customers,
                    'accounts_id'   => $account_v['account_name'],
                    'money'         => $account_v['money'],
                    'settlementtype'=> $account_v['name'],
                    'number'        => $account_v['number'],
                    'remark'        => $account_v['remark'],
                    'moneys'        => $list_v['money'],
                    'write_off'     => $list_v['write_off'],
                    'discount'      => $list_v['discount'],
                    'advance'       => $list_v['advance'],
                    'staff_member'  => $staff_member,
                    'examine'       => $examine,
                    'preparation'   => $preparation,
                    'remarks'       => $list_v['remarks'],
                    'print_num'     => $list_v['print_num'],
                    'createtime'    => date('Y-m-d H:i', $list_v['createtime']),
                ];
            }
        }
        $result = array("total" => count($list), "rows" => $lists);
        return json($result);

    }

    public function get_goodssalesoperation_log()
    {
        $ids = $this->request->param("id");
        //操作记录
        $log=OperationLog::getList(OperationLog::CONTRACT_TYPE, $ids);
        $result = array("total" => count($log), "rows" => $log);

        return json($result);
    }

    public function add($ids = null,$order_id=null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $examine= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');
                $params = $this->preExcludeFields($params);

                if(empty($params['purchase_code'])){
                    $this->error('请填写单据编号');
                }

                $admin = Session::get('admin');
                if($params['now_pay_money']>0){
                    if(empty($params['account'])){
                        $this->error('请选择结算账户');
                    }
                    $all_now_pay_money = $now_pay_money = trim($params['now_pay_money']);
                }else{
                    $all_now_pay_money = $now_pay_money = 0;
                }

                $set= Db::name('kuerp_sets')->where(['name'=>'serial'])->value('is_checked');
                $batch= Db::name('kuerp_sets')->where(['name'=>'batch'])->value('is_checked');
                $auxiliary_status= Db::name('kuerp_sets')->where(['name'=>'auxiliary'])->value('is_checked');

                //销售员 当前登录为销售员时
                $saleList = $this->model->getSaleList($this->auth->staff_member_id ?? 0);
                $sale_user = (int)$params['sale_user'];
                $sale_user_name = '';
                // if ($this->auth->is_sale) {
                //     $sale_user = $this->auth->staff_member_id;
                // }
                if(!empty($sale_user)){
                    foreach ($saleList as $sale_k=>$sale_v) {
                        if ($sale_user == $sale_v['id']) {
                            $sale_user_name = $sale_v['name'];
                            break;
                        }
                    }
                } else {
                    $this->error('请选择销售员');
                }
                $data = [];
                $number = 0;$all_money = 0;$purchase_order_id = '';$tax_money=0;$money_tax_price=0;
                $back_money = 0;//返款金额
                $goods_number = 0;//询价条数
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number += (float)$params['number'][$k];
                        //判断金额是否一致
                        $infototal = round((float)$params['number'][$k] * (float)$params['unit_price'][$k] - (float)$params['back_money'][$k], 2);
                        if($infototal!=$params['all_money'][$k]){
                            $params['all_money'][$k] = $infototal;
                            $params['money_tax_price'][$k] = $infototal;
                        }
                        $all_money += (float)$params['all_money'][$k];
                        $tax_money += (float)$params['tax_money'][$k];
                        $money_tax_price += (float)$params['money_tax_price'][$k];
                        $back_money += (float)$params['back_money'][$k];

                        if(!empty($params['purchase_order_id'][$k])){
                            $purchase_order_id = $params['purchase_order_id'][$k];
                        }

                        if(!isset($params['stores_id'][$k]) || empty($params['stores_id'][$k])){
                            $this->error('请选择仓库');
                        }

                        unset($pay_money);unset($pay_status);
                        if($now_pay_money>0){
                            if($now_pay_money-$params['money_tax_price'][$k]>=0){
                                $pay_status = 1;
                                $pay_money = $params['money_tax_price'][$k];
                                $now_pay_money -= $pay_money;
                            }else{
                                $pay_status = 2;
                                $pay_money = $now_pay_money;
                                $now_pay_money -= $now_pay_money;
                            }
                        }

                        $goods = Db::name('kuerp_goods')->where(['goods_code'=>$v])->field('id,serial,batch,auxiliary')->find();
                        $batch_data = Db::name('kuerp_goods_batch')->where(['id'=>$params['batch_id'][$k]])->find();
                        if ($goods['auxiliary']==1 && empty($params['goods_attr'][$k]) && $auxiliary_status==1){
                            return ['status'=>500,'msg'=>'请选择商品'.$v.'属性'];
                        }

                        if(in_array($v,array_merge($this->goods_code_caijia,$this->goods_code_xunjia))){  //判断是否有材价通账号
                            if(empty($params['remark'][$k])){
                                $this->error('请在商品'.$v.'{备注栏}里面输入续费的材价通手机号');
                            }
                            if(empty($params['goods_number'][$k]) && in_array($v,$this->goods_code_xunjia)){
                                $this->error('商品'.$v.'未输入续费询价条数');
                            }
                            if(empty($params['year_number'][$k]) && in_array($v,$this->goods_code_caijia)){
                                $this->error('商品'.$v.'未输入续费时长');
                            }
                            if(!empty($params['remark'][$k])){
                                $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$params['remark'][$k]));
                            }
                            $caijiaUserModel = new \app\common\model\caijiatong\User();
                            foreach ($remark as $remark_mobile){
                                $caijia_user = $caijiaUserModel->getUserInfo($remark_mobile);
                                if(!$caijia_user){
                                    $this->error('材价通会员账号'.$remark_mobile.'不存在');
                                }
                            }

                        }
                        if(in_array($v,$this->goods_code_wls)){  //判断网络锁是否存在
                            if(empty($params['remark'][$k])){
                                $this->error('请在商品'.$v.'{备注栏}里面输入续费的网络锁锁内码');
                            }
                            if(empty($params['year_number'][$k])){
                                $this->error('商品'.$v.'未输入续费时长');
                            }
                            if(!empty($params['remark'][$k])){
                                $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$params['remark'][$k]));
                            }
                            $caijiaUserSoftwareModel = new \app\common\model\caijiatong\UserSoftware();
                            foreach ($remark as $remark_mobile){
                                if (((string)$remark_mobile)[0] != '2' && substr((string)$remark_mobile, 0, 5) != 'NBGV0') {
                                    $this->error($remark_mobile.'不是网络锁');
                                }
                                $caijia_user = $caijiaUserSoftwareModel->getUsersoftwareInfo($remark_mobile);
                                if(!$caijia_user){
                                    $this->error('网络锁'.$remark_mobile.'不存在');
                                }
                            }
                        }


                        $goods_batch_info = [];
                        if($goods['batch']==1 && $batch==1){
                            if(empty($params['batch'][$k])){
                                $this->error('请选择生产批次');
                            }
                            if(empty($batch_data)){
                                $this->error('生产批次不存在');
                            }
                            $goods_batch_info = [
                                'batch_id'    => isset($batch_data['id'])?$batch_data['id']:'',
                                'goods_id'    => $goods['id'],
                                'goods_code'  => $params['goods_code'][$k],
                                'attribute_id'=>isset($params['goods_attr'][$k])?$params['goods_attr'][$k]:0,
                                'goods_unit'  =>  (int)$params['goods_unit'][$k],
                                'stores_id'   => $params['stores_id'][$k],
                                'stock'       => (float)$params['number'][$k],
                                'number'      => (float)$params['number'][$k],
                                'batch_name'  => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                                'manufacture' => strtotime($params['manufacture'][$k]),
                                'guarantee'   => $params['guarantee'][$k],
                                'validity'    => strtotime($params['validity'][$k]),
                                'status'      => '0',
                                'type'        => 2,
                                'createtime'  => time(),
                                'updatetime'  => time(),
                            ];
                        }

                        $serial_code = [];
                        if(isset($params['period_period'][$k]) && $goods['serial']==1 && $set==1){
                            if(empty($params['period_period'][$k]) && empty($params['serials'])){
                                $this->error('请输入锁编号或者点击数量栏选择序列号');
                            }
                            if (!empty($params['period_period'][$k])) {
                                $period_period = unserialize($params['period_period'][$k]);
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    $serial_code[] = $period_period_v['serial'];
                                }
                                $where = [];
                                $where['serial'] = ['in',$serial_code];
                                if(!empty($params['purchase_id'][$k])){
                                    $where['purchase_code'] = $params['purchase_id'][$k];
                                }
                                $goods_serial = Db::name('kuerp_goods_serial')->where($where)->column('serial');
                                if(empty($goods_serial)){
                                    $this->error('商品序列号不存在');
                                }
                                foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                    if(!in_array($serial_code_v,$goods_serial)){
                                        $this->error($serial_code_v.'商品序列号不存在');
                                    }
                                }
                                $goods_serials = Db::name('kuerp_goods_serial')->where(['status'=>['in',[2,3]],'serial'=>['in',$serial_code]])->column('serial');
                                if(!empty($goods_serials)){
                                    $goods_serials = implode(',',$goods_serials);
                                    $this->error('商品序列号'.$goods_serials.'已经待出库，不可重复出库');
                                }
                            }
                        }

                        if(!empty($params['info_id'][$k])){
                            $unit_id_order = Db::name('kuerp_goods_sales_order_info')->where(['id'=>$params['info_id'][$k]])->value('goods_unit');
                            if(!empty($unit_id_order) && $unit_id_order!=$params['goods_unit'][$k]){
                                $this->error('选择的商品单位与源销货订单不一致，保存失败');
                            }
                        }
                        //时间期限
                        $start_date = $end_date = null;
                        if(!empty($params['date_range'][$k])){
                            $date_range = str_replace(' - ', ',', $params['date_range'][$k]);
                            $arr = array_slice(explode(',', $date_range), 0, 2);
                            $start_date = $arr[0];
                            $end_date = $arr[1];
                        }
                        //询价条数
                        $goods_number += !empty($params['goods_number'][$k]) ? (float)$params['goods_number'][$k] : 0;
                        $data[] = [
                            'purchase_code'     =>  $params['purchase_code'],
                            'purchase_type'     =>  $params['purchase_type'],
                            'purchase_time'     =>  strtotime($params['purchase_time']),
                            'customers_id'      =>  (int)$params['customers_id'],//客户
                            'sale_user'         =>  $sale_user,//销售员
                            'sale_user_name'    =>  $sale_user_name,//销售员名称
                            'receiving_address' =>  $params['receiving_address'],

                            'goods_code'        =>  $v,//商品信息
                            'goods_note'        =>  $params['goods_note'][$k],
                            'goods_unit'        =>  (float)$params['goods_unit'][$k],
                            'goods_type'        =>  $params['goods_type'][$k],//商品类型

                            'stores_id'         =>  $params['stores_id'][$k],
                            'allow_stock'       =>  (float)$params['allow_stock'][$k],
                            'order_info_id'     =>  (float)$params['info_id'][$k],
                            'number'            =>  (float)$params['number'][$k],
                            'default_unit'      =>  (float)$params['default_unit'][$k],
                            'basic_nmber'       =>  (float)$params['basic_nmber'][$k],
                            'unit_price'        =>  (float)$params['unit_price'][$k],
                            'cost_price'        =>  0,
                            'discount'          =>  (float)$params['discount'][$k],
                            'dis_money'         =>  (float)$params['dis_money'][$k],
                            'back_money'        =>  (float)$params['back_money'][$k],
                            'all_money'         =>  (float)$params['all_money'][$k],
                            'remark'            =>  $params['remark'][$k],

                            'goods_attr'        =>  (float)$params['goods_attr'][$k],
                            'tax_included'      =>  (float)$params['tax_included'][$k],
                            'tax_rate'          =>  (float)$params['tax_rate'][$k],
                            'tax_money'         =>  (float)$params['tax_money'][$k],
                            'money_tax_price'   =>  (float)$params['money_tax_price'][$k],

                            'batch_id'          => isset($batch_data['id'])?$batch_data['id']:0,
                            'batch_name'        => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                            'manufacture'       => strtotime($params['manufacture'][$k]),
                            'guarantee'         => $params['guarantee'][$k],
                            'validity'          => strtotime($params['validity'][$k]),

                            'preferential_rate' =>  (float)$params['preferential_rate'],
                            'preferential_money'=>  (float)$params['preferential_money'],
                            'real_money'        =>  (float)$params['real_money'],
                            'purchase_money'    =>  (float)$params['purchase_money'][$k],
                            'preparation_id'    =>  $admin['id'],
                            'operation_id'      =>  $admin['id'],

                            'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                            'pay_money'         =>  isset($pay_money)?$pay_money:0,
                            'account'           =>  isset($pay_status)?$params['account']:0,

                            'purchase_order_id' =>  $params['purchase_order_id'][$k] ?? '',

                            'createtime'        => time(),
                            'updatetime'        => time(),
                            'period'            =>  $params['period_period'][$k]===''?null:$params['period_period'][$k],
                            'serial_code'       => $serial_code,
                            'goods_batch_info'  => $goods_batch_info,
                            'start_date'        => $start_date,
                            'end_date'          => $end_date,
                            'year_number'       => (float)$params['year_number'][$k] ?? 0,
                            'goods_number'      => (float)$params['goods_number'][$k] ?? 0,
                        ];
                    }
                }
                if (!$all_money) {
                    // $this->error('订单错误，金额为0');
                }
                $preferential_money = (float)$params['preferential_money'];
                if(!empty($data)){
                    if($all_now_pay_money>0){
                        if($all_now_pay_money+$preferential_money-$money_tax_price>=0){
                            $pay_status = 1;
                            $pay_money = $money_tax_price-$preferential_money;
                        }else{
                            $pay_status = 2;
                            $pay_money = $all_now_pay_money;
                        }
                    }

                    $row = [
                        'purchase_code'     =>  $params['purchase_code'],
                        'purchase_type'     =>  $params['purchase_type'],
                        'purchase_time'     =>  strtotime($params['purchase_time']),
                        'customers_id'      =>  (int)$params['customers_id'],//客户
                        'sale_user'         =>  $sale_user,//销售员
                        'sale_user_name'    =>  $sale_user_name,//销售员名称
                        'receiving_address' =>  $params['receiving_address'],
                        'customers_money'   =>  (float)$params['customers_money'],

                        'number'            =>  $number,
                        'all_money'         =>  $all_money,

                        'tax_money'         =>  $tax_money,//税
                        'money_tax_price'   =>  $money_tax_price,//价税合计
                        'back_money'        =>  $back_money,//返款金额

                        'preferential_rate' =>  (float)$params['preferential_rate'],
                        'preferential_money'=>  (float)$params['preferential_money'],
                        'real_money'        =>  $all_money,//(float)$params['real_money'],
                        'purchase_money'    =>  (float)$params['costs'],
                        'note'              =>  $params['note'],
                        'buy_type'          =>  $params['buy_type'] ?? '',
                        'buy_version'       =>  $params['buy_version'] ?? '',
                        'customers_users'   =>  $params['customers_users'] ?? '',
                        'serials'           =>  $params['serials'] ?? '',
                        'lock_code'         =>  $params['lock_code'] ?? '',
                        'receipt'           =>  $params['receipt'] ?? '',
                        'preparation_id'    =>  $admin['id'],
                        'operation_id'      =>  $admin['id'],

                        'arrears'           =>  $all_money - $all_now_pay_money,//$params['arrears'],
                        'all_arrears'       =>  $params['add_arrears'],

                        'purchase_order_id' =>  $purchase_order_id,

                        'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                        'pay_money'         =>  isset($pay_money)?$pay_money:0,
                        'account'           =>  isset($pay_status)?$params['account']:0,
                        'cost_data'         =>  isset($params['cost_data'])?$params['cost_data']:null,
                        'createtime'        => time(),
                        'updatetime'        => time(),
                        'goods_number'      => $goods_number,
                    ];
                    //是否在审核流程中
                    //获取审批流程
                    $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
                    if (!empty($flows)){
                        $flows['flow_items'] = json_decode($flows['flow_items'], true);
                        //判断流程中是否有当前用户审核
                        $examine_index = 0;
                        foreach ($flows['flow_items'] as $key => $value) {
                            if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                                $examine_index = $key + 1;
                                // break;
                            }
                        }
                        if ($examine_index > 0) {
                            $row['examine_id'] = $this->auth->id;
                            $row['examine_adminids'] = $this->auth->id;
                            $row['check_history_uids'] = $this->auth->id;
                            $row['examine_index'] = $examine_index;
                        }
                    }
                } else {
                    $this->error('请选择商品');
                }

                if($this->model->where(['purchase_code'=>trim($params['purchase_code'])])->find()){
                    $this->error('单据编号已占用');
                }
                if($purchase_order_id){
                    $order_id = Db::name('kuerp_goods_sales_order')->where(['purchase_code'=>$purchase_order_id])->value('id');
                }

                //附件记录开始
                $enclosureLog = [];
                if(isset($params['enclosure']) && !empty($params['enclosure'])){//选择了原始单据
                    $enclosure = explode(',',$params['enclosure']);
                    $enclosurelist = Db::name('kuerp_enclosure')->where(['id'=>['in',$params['enclosure']]])->select();
                    if(sizeof($enclosurelist)!=sizeof($enclosure)){
                        $this->error('选择的原始单据有误，请重新选择');
                    }else{
                        foreach ($enclosure as $k=>$v){
                            $enclosureLog[] = [
                                'enclosure_id'  => $v,
                                'purchase_code' => $params['purchase_code'],
                                'type'          => '5',
                            ];
                        }
                    }
                    unset($params['enclosure']);
                }
                //附件记录结束

                $info_id = Db::name('kuerp_goods_sales_order_info')->where(['purchase_code'=>$params['purchase_code']])->column('id');
                $result = false;
                Db::startTrans();
                try {
                    if(!empty($row)){
                        $result = $this->model->insertGetId($row);
                    }

                    //添加附件记录
                    if(!empty($enclosureLog)){
                        foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                            $enclosureLog[$enclosureLog_k]['order_id'] = $result;
                        }
                        Db::name('kuerp_enclosure_log')->insertAll($enclosureLog);
                    }
                    //添加附件记录结束

                    if(!empty($info_id)){
                        Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
                    }
                    Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$params['purchase_code']])->delete();
                    foreach ($data as $data_k=>$data_v){
                        $goods_serial = $data_v['serial_code'];
                        unset($data_v['serial_code']);
                        if ($data_v['real_money'] != $all_money) {
                            $data_v['real_money'] = $all_money;
                        }

                        $goods_batch_info = $data_v['goods_batch_info'];
                        unset($data_v['goods_batch_info']);

                        $purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v);

                        //批次
                        if($goods_batch_info){
                            $goods_batch_info['purchase_info_id'] = $purchase_id;
                            Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info);
                        }

                        if(!empty($goods_serial)){
                            Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
                                'status'=>'3',
                                'sale_id' => $purchase_id,
                                'sale_code' => $data_v['purchase_code']
                            ]);
                        }

                        if(!empty($data_v['order_info_id'])){
                            Db::name('kuerp_goods_saleord_info')->insert([
                                'order_id'=>$data_v['order_info_id'],
                                'purchase_id'=>$purchase_id,
                                'number'=>$data_v['number'],
                                'money'=>$data_v['pay_money'],
                                'all_money'=>$data_v['all_money'],
                                'tax_rate'=>$data_v['tax_rate'],
                                'tax_money'=>$data_v['tax_money'],
                                'money_tax_price'=>$data_v['money_tax_price']
                            ]);
                        }
                    }
                    if(!empty($purchase_order_id)){
                        if($result){
                            Db::name('kuerp_goods_saleord')->insert(['order_id'=>$order_id,'purchase_id'=>$result]);
                        }
                    }
                    $flow = Flows::getFlowByTypes(Flows::CONTRACT_STATUS);
                    //发送审批通知
                    Flows::sendStepRecord($flow, Flows::CONTRACT_STATUS, $result);
                    OperationLog::createLog(OperationLog::CONTRACT_TYPE, $result, '创建订单');
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if (isset($result) && $result !== false) {
                    if($examine!=1){
                        try {
                            $exa = $this->examine($result,1);
                        } catch (Exception $e) {
                        }
                        if(!isset($exa) || $exa['status']!=1){
                            $exa = $this->examine($result,1);
                            try {
                                $this->del($result);
                            } catch (Exception $e) {
                            }
                            $this->error($exa['msg']);
                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $code = (new Goods())->getCodes('',11);
        $this->view->assign("code", $code);

        $row = Db::name('kuerp_goods_sales_order')->where(['id'=>$ids])->find();

        $last_customer = \think\Db::name('kuerp_sets')->where(['name'=>'customer'])->value('is_checked');
        $set_customer = '';
        if($last_customer){
            $set_customer = Db::name('kuerp_goods_sales')->where((new Goods())->setWhere())->order('id','DESC')->value('customers_id');
        }
        $address = Db::name('kuerp_customers')->where((new Goods())->setWhere(['id'=>$set_customer]))->value('getgoods_address');
        $last_read = \think\Db::name('kuerp_sets')->where(['name'=>'last_read'])->value('is_checked');
        $sale_user = '';
        if($last_read){
            $sale_user = Db::name('kuerp_goods_sales')->where((new Goods())->setWhere())->order('id','DESC')->value('sale_user');
        }
        if ($this->auth->is_sale) {
            $sale_user = $this->auth->staff_member_id;
        }
        $give_account = 0;$real_money = 0;$arrears = 0;$real_moneys = 0;
        if($row){
            $purchase_info = Db::name('kuerp_goods_sales_order_info')->where(['purchase_code'=>$row['purchase_code']])->select();
            foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                $purord_info = Db::name('kuerp_goods_saleord_info')->where(['order_id'=>$purchase_info_v['id']])->field('sum(number) as number,sum(money) as money')->select();
                $gp_number = isset($purord_info[0]['number'])?$purord_info[0]['number']:0;
                $real_money += isset($purord_info[0]['money'])?$purord_info[0]['money']:0;
                $real_moneys += $purchase_info_v['money_tax_price']-$purchase_info_v['preferential_money']-($gp_number)*$purchase_info_v['tax_included'];
                if($purchase_info_v['number']-$gp_number<=0){
                    unset($purchase_info[$purchase_info_k]);
                }else{
                    $unit = json_decode($this->getUnit($purchase_info_v['goods_code']),true);
                    foreach ($unit['unit'] as $unit_k=>$unit_v){
                        if($unit_v['id']==$purchase_info_v['goods_unit']){
                            $purchase_info[$purchase_info_k]['basic_nmber'] = ($purchase_info_v['number']-$gp_number)*$unit_v['basic_nmber'];
                        }
                    }
                    $purchase_info[$purchase_info_k]['unit'] = $unit;
                    $purchase_info[$purchase_info_k]['all_money'] = ($purchase_info_v['number']-$gp_number)*$purchase_info_v['unit_price'];
                    $purchase_info[$purchase_info_k]['money_tax_price'] = ($purchase_info_v['number']-$gp_number)*$purchase_info_v['tax_included'];
                    $purchase_info[$purchase_info_k]['tax_money'] = ($purchase_info_v['number']-$gp_number)*$purchase_info_v['tax_money']/$purchase_info_v['number'];
                    $purchase_info[$purchase_info_k]['dis_money'] = $purchase_info[$purchase_info_k]['all_money']*($purchase_info_v['discount'])/100;
                    $arrears += $purchase_info[$purchase_info_k]['all_money'] -= $purchase_info[$purchase_info_k]['dis_money'];
                    $purchase_info[$purchase_info_k]['purchase_number'] = $purchase_info_v['number']-$gp_number;
                    $goods = Db::name('kuerp_goods')->where(['goods_code'=>$purchase_info_v['goods_code']])->field('batch,serial')->find();
                    $purchase_info[$purchase_info_k]['goods'] = $goods;
                }
            }
            $give_account = Db::name('kuerp_customers')->where(['id'=>$row['customers_id']])->value('need_receive_account');
        }else{
            $row['customers_id'] = $set_customer;
            $row['receiving_address'] = $address;
            $row['sale_user'] = $sale_user;
        }
        $row['real_money'] = $real_moneys;
        $purchase_info = isset($purchase_info)?$purchase_info:[];
        $this->assignconfig("give_account", $give_account);
        $give_account = $give_account+$real_money+$row['real_money'];

        if(!empty($order_id)){
            $order = Db::name('kuerp_user_order')->where(['id'=>$order_id])->find();
            if($order){
                $purchase_info = [];
                $customers_id = Db::name('kuerp_user')->where(['id'=>$order['user_id']])->value('customers_id');
                $customers = Db::name('kuerp_customers')->where(['id'=>$customers_id])->find();
                $goods_list = Db::name('kuerp_user_orderinfo')->where(['order_id'=>$order['id']])
                    ->select();
                foreach ($goods_list as $goods_list_k=>$goods_list_v){
                    $goods = Db::name('kuerp_goods')->where(['id'=>$goods_list_v['goods_id']])->find();
                    $unit = json_decode($this->getUnit($goods['goods_code']),true);

                    $goods_list_v['basic_number'] = $goods_list_v['number'];
                    foreach ($unit['unit'] as $unit_k=>$unit_v){
                        if($unit_v['id']==$goods_list_v['goods_unit']){
                            $goods_list_v['basic_number'] = ($goods_list_v['number'])*$unit_v['basic_nmber'];
                        }
                    }

                    $purchase_info[] = [
                        'id' => '',
                        'unit'  => $unit,
                        'goods_code' => $goods['goods_code'],
                        'goods_note' => $goods['note'],
                        'goods_attr' => $goods_list_v['goods_attr'],
                        'goods_unit' => $goods_list_v['goods_unit'],
                        'goods_type' => $goods_list_v['goods_type'],
                        'stores_id'  => '',
                        'allow_stock'=> $goods['inventory'],
                        'purchase_number' => $goods_list_v['number'],
                        'default_unit' => $goods['unit_id'],
                        'basic_nmber'=> $goods_list_v['basic_number'],
                        'unit_price' => $goods_list_v['price'],
                        'tax_included' => $goods_list_v['price'],
                        'discount'=> 0,
                        'dis_money' => 0,
                        'all_money' => $goods_list_v['money'],
                        'tax_rate'=> 0,
                        'tax_money' => 0,
                        'money_tax_price' => $goods_list_v['money'],
                        'purchase_money' => '',
                        'remark'=> '',
                        'purchase_code' => '',
                        'order_info_id' => $goods_list_v['id'],
                    ];
                }
                $row['customers_id'] = $customers_id;
                $row['receiving_address'] = $order['address'];
                $row['real_money'] = $order['order_price'];
                $row['order_id'] = $order['id'];
                $give_account = $customers['need_receive_account'] + $order['order_price'];
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("purchase_info", $purchase_info);
        $this->view->assign("give_account", $give_account);

        //查询原始单据
        $enclosure_id = Db::name('kuerp_enclosure_log')->where(['order_id'=>$ids,'type'=>'4'])->column('enclosure_id');
        if(!empty($enclosure_id)){
            $this->assign('enclosure_count',sizeof($enclosure_id));
            $enclosure_id = implode(',',$enclosure_id);
        }else{
            $enclosure_id = '';
        }
        $this->assign('enclosure_ids',$enclosure_id);
        $stores_id = '';
        if ($this->auth->is_sale) {
            $stores_id = $this->auth->stores_info['id'] ?? '';
        }
        $this->assignconfig("stores_id", $stores_id);

        $this->assignconfig("suppliersList", $this->model->getSuppliersList());
        $this->assignconfig("expendTypeList", $this->model->getExpendTypeList());
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        //是否有权限审核后编辑
        $enableEdit = $this->auth->check('kuerp/goods_sales/approvedEdit');
        if ($this->request->isPost()) {
            $examine= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');
            if($row['examine_status']==1 && $examine==1 && !$enableEdit){
                $this->error('不能编辑已审核的数据');
            }
            if($row['check_status']==1){
                $this->error('不能编辑已对单的数据');
            }
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $old_purchase_code = $params['old_purchase_code'];unset($params['old_purchase_code']);
                $info_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$old_purchase_code])->column('id');

                if(empty($params['purchase_code'])){
                    $this->error('请填写单据编号');
                }

                $admin = Session::get('admin');
                if($params['now_pay_money']>0){
                    if(empty($params['account'])){
                        $this->error('请选择结算账户');
                    }
                    $all_now_pay_money = $now_pay_money = trim($params['now_pay_money']);
                }else{
                    $all_now_pay_money = $now_pay_money = 0;
                }

                $set= Db::name('kuerp_sets')->where(['name'=>'serial'])->value('is_checked');
                $batch= Db::name('kuerp_sets')->where(['name'=>'batch'])->value('is_checked');
                $auxiliary_status= Db::name('kuerp_sets')->where(['name'=>'auxiliary'])->value('is_checked');
                //销售员 当前登录为销售员时
                $saleList = $this->model->getSaleList(0);
                $sale_user = (int)$params['sale_user'];
                $sale_user_name = '';
                // if ($this->auth->is_sale) {
                //     $sale_user = $this->auth->staff_member_id;
                // }
                if(!empty($sale_user)){
                    foreach ($saleList as $sale_k=>$sale_v) {
                        if ($sale_user == $sale_v['id']) {
                            $sale_user_name = $sale_v['name'];
                            break;
                        }
                    }
                }
                //审核通过后修改
                if ($row['examine_status']==1 && $examine==1 && $enableEdit) {
                    // $purchase_id = Db::name('kuerp_goods_saleexc')->where(['purchase_id'=>['in', $info_id],'type'=>'2'])->column('exchange_id');
                    // if(!empty($purchase_id)){
                    //     $this->error('不能编辑已生成退货单的数据');
                    // }
                    $purchase_id = Db::name('kuerp_collection_sale')->where(['purchase_number'=>$params['purchase_code']])->find();
                    if(!empty($purchase_id)){
                        $this->error('不能编辑已生成收款单的数据');
                    }
                    // $purchase_id = Db::name('kuerp_writeoff_info')->where(['purchase_number'=>$params['purchase_code']])->find();
                    // if(!empty($purchase_id)){
                    //     $this->error('不能编辑已生成核销单的数据');
                    // }

                    $update_data = [];
                    $number = 0;$all_money = 0;$tax_money=0;$money_tax_price=0;
                    $back_money = 0;//返款金额
                    $goods_number = 0;//询价条数
                    //锁编号是否有修改
                    $ischangeserial = false;
                    //锁日志
                    $serial_log = [];
                    //获取订单商品信息
                    $salesInfo = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->column('*', 'id');
                    if(empty($salesInfo)) $this->error('订单商品信息不存在');
                    $goods_codes = array_unique(array_column($salesInfo, 'goods_code'));
                    $goodsList = Db::name('kuerp_goods')->where(['goods_code'=>['in', $goods_codes]])->column('id,serial,batch,auxiliary', 'goods_code');
                    foreach ($params['sales_info_id'] as $k=>$v){
                        if (empty($v)) continue;
                        if (empty($salesInfo[$v])) {
                            $this->error('订单产品信息不存在');
                        }
                        $old_sales_info = $salesInfo[$v];
                        if ($old_sales_info['number'] != $params['number'][$k]) {
                            $this->error('订单产品数量不可更改');
                        }
                        //判断金额是否一致
                        $infototal = round((float)$params['number'][$k] * (float)$params['unit_price'][$k] - (float)$params['back_money'][$k], 2);
                        if($infototal!=$params['all_money'][$k]){
                            $params['all_money'][$k] = $infototal;
                            $params['money_tax_price'][$k] = $infototal;
                        }
                        $number+=$params['number'][$k];
                        $all_money+=$params['all_money'][$k];
                        $tax_money += (float)$params['tax_money'][$k];
                        $money_tax_price += (float)$params['money_tax_price'][$k];
                        $back_money += (float)$params['back_money'][$k];
                        unset($pay_money);unset($pay_status);
                        if($now_pay_money>0){
                            if($now_pay_money-$params['money_tax_price'][$k]>=0){
                                $pay_status = 1;
                                $pay_money = $params['money_tax_price'][$k];
                                $now_pay_money -= $pay_money;
                            }else{
                                $pay_status = 2;
                                $pay_money = $now_pay_money;
                                $now_pay_money -= $now_pay_money;
                            }
                        }
                        $goods = $goodsList[$old_sales_info['goods_code']];
                        $batch_data = Db::name('kuerp_goods_batch')->where(['id'=>$params['batch_id'][$k]])->find();
                        if ($goods['auxiliary']==1 && empty($params['goods_attr'][$k]) && $auxiliary_status==1){
                            return ['status'=>500,'msg'=>'请选择商品'.$v.'属性'];
                        }
                        $goods_batch_info = [];
                        // if($goods['batch']==1 && $batch==1){
                        //     if(empty($params['batch'][$k])){
                        //         $this->error('请选择生产批次');
                        //     }
                        //     if(empty($batch_data)){
                        //         $this->error('生产批次不存在');
                        //     }
                        //     $goods_batch_info = [
                        //         'batch_id'    => isset($batch_data['id'])?$batch_data['id']:'',
                        //         'goods_id'    => $goods['id'],
                        //         'goods_code'  => $params['goods_code'][$k],
                        //         'attribute_id'=>isset($params['goods_attr'][$k])?$params['goods_attr'][$k]:0,
                        //         'goods_unit'  =>  (int)$params['goods_unit'][$k],
                        //         'stores_id'   => $params['stores_id'][$k],
                        //         'stock'       => (float)$params['number'][$k],
                        //         'number'      => (float)$params['number'][$k],
                        //         'batch_name'  => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                        //         'manufacture' => strtotime($params['manufacture'][$k]),
                        //         'guarantee'   => $params['guarantee'][$k],
                        //         'validity'    => strtotime($params['validity'][$k]),
                        //         'status'      => '0',
                        //         'type'        => 2,
                        //         'createtime'  => time(),
                        //         'updatetime'  => time(),
                        //     ];
                        // }

                        $serial_code = [];
                        if(isset($params['period_period'][$k]) && $goods['serial']==1 && $set==1){
                            //没有填锁编号
                            if(empty($params['period_period'][$k]) && empty($params['serials'])){
                                $this->error('请输入锁编号或者点击数量栏选择序列号');
                            }
                            //判断锁编号是否修改
                            if (!empty($params['period_period'][$k]) && $params['period_period'][$k] != $old_sales_info['period']) {
                                $ischangeserial = true;
                                $period_period = unserialize($params['period_period'][$k]);
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    $serial_code[] = $period_period_v['serial'];
                                }
                                $where = [];
                                $where['serial'] = ['in',$serial_code];
                                if(!empty($params['purchase_id'][$k])){
                                    $where['purchase_code'] = $params['purchase_id'][$k];
                                }
                                $goods_serial = Db::name('kuerp_goods_serial')->where($where)->column('serial');
                                if(empty($goods_serial)){
                                    $this->error('商品序列号不存在');
                                }
                                foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                    if(!in_array($serial_code_v,$goods_serial)){
                                        $this->error($serial_code_v.'商品序列号不存在');
                                    }
                                }
                                $goods_serials = Db::name('kuerp_goods_serial')->where(['status'=>['in',[2,3]],'serial'=>['in',$serial_code],'sale_id'=>['not in',$info_id]])->column('serial');
                                if(!empty($goods_serials)){
                                    $goods_serials = implode(',',$goods_serials);
                                    $this->error('商品序列号'.$goods_serials.'已经待出库，不可重复出库');
                                }

                                foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                                    $serial_log[] = (new Goods())->setDataInfo([
                                        'goods_id'=>$goods['id'],
                                        'stores_id'=>$old_sales_info['stores_id'],
                                        'attribute_id'=> 0,
                                        'serial'=>$goods_serial_v,
                                        'business_type'=>'4',
                                        'store_status'=>'2',
                                        'remarks' => $params['remark'][$k],
                                        'purchase_id'=>$old_sales_info['id'],
                                        'customer_id'=>$old_sales_info['customers_id'],
                                        'purchase_code'=>$old_sales_info['purchase_code'],
                                        'purchase_time' => $old_sales_info['purchase_time'],
                                        'createtime'  => time(),
                                        'updatetime'  => time(),
                                    ]);
                                }
                            }
                        }

                        if(!empty($params['info_id'][$k])){
                            $unit_id_order = Db::name('kuerp_goods_sales_order_info')->where(['id'=>$params['info_id'][$k]])->value('goods_unit');
                            if(!empty($unit_id_order) && $unit_id_order!=$params['goods_unit'][$k]){
                                $this->error('选择的商品单位与源购货订单不一致，保存失败');
                            }
                        }
                        //时间期限
                        $start_date = $end_date = null;
                        if(!empty($params['date_range'][$k])){
                            $date_range = str_replace(' - ', ',', $params['date_range'][$k]);
                            $arr = array_slice(explode(',', $date_range), 0, 2);
                            $start_date = $arr[0];
                            $end_date = $arr[1];
                        }

                        //询价条数
                        $goods_number += !empty($params['goods_number'][$k]) ? (float)$params['goods_number'][$k] : 0;
                        $update_data[] = [
                            'id'                =>  $v,
                            'receiving_address' =>  $params['receiving_address'],
                            // 'goods_code'        =>  $params['goods_code'][$k],
                            'goods_unit'        =>  (int)$params['goods_unit'][$k],
                            'goods_type'        =>  $params['goods_type'][$k],

                            'number'            =>  (float)$params['number'][$k],
                            'default_unit'      =>  (float)$params['default_unit'][$k],
                            'basic_nmber'       =>  (float)$params['basic_nmber'][$k],
                            'unit_price'        =>  (float)$params['unit_price'][$k],
                            'cost_price'        =>  0,
                            'discount'          =>  (float)$params['discount'][$k],
                            'dis_money'         =>  (float)$params['dis_money'][$k],
                            'back_money'        =>  (float)$params['back_money'][$k],
                            'all_money'         =>  (float)$params['all_money'][$k],
                            'remark'            =>  $params['remark'][$k],

                            'goods_attr'        =>  (float)$params['goods_attr'][$k],
                            'tax_included'      =>  (float)$params['tax_included'][$k],
                            'tax_rate'          =>  (float)$params['tax_rate'][$k],
                            'tax_money'         =>  (float)$params['tax_money'][$k],
                            'money_tax_price'   =>  (float)$params['money_tax_price'][$k],

                            'batch_id'          => isset($batch_data['id'])?$batch_data['id']:'',
                            'batch_name'        => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                            'manufacture'       => strtotime($params['manufacture'][$k]),
                            'guarantee'         => $params['guarantee'][$k],
                            'validity'          => strtotime($params['validity'][$k]),

                            'preferential_rate' =>  (float)$params['preferential_rate'],
                            'preferential_money'=>  (float)$params['preferential_money'],
                            'real_money'        =>  (float)$params['real_money'],
                            'purchase_money'    =>  (float)$params['purchase_money'][$k],
                            'preparation_id'    =>  $admin['id'],
                            'operation_id'      =>  $admin['id'],

                            'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                            'pay_money'         =>  isset($pay_money)?$pay_money:0,
                            'account'           =>  isset($pay_status)?$params['account']:0,

                            'updatetime'        => time(),
                            'period'            =>  $params['period_period'][$k]===''?null:$params['period_period'][$k],
                            'serial_code'       => $serial_code,
                            'goods_batch_info'  => $goods_batch_info,
                            'start_date'        => $start_date,
                            'end_date'          => $end_date,
                            'year_number'          => !empty($params['year_number'][$k]) ? (float)$params['year_number'][$k] : 0,
                            'goods_number'          => !empty($params['goods_number'][$k]) ? (float)$params['goods_number'][$k] : 0,
                        ];
                    }
                    
                    $preferential_money = (float)$params['preferential_money'];
                    if(!empty($update_data)){
                        if($all_now_pay_money>0){//当次支付金额
                            if($all_now_pay_money+$preferential_money-$money_tax_price>=0){
                                $pay_status = 1;
                                $pay_money = $money_tax_price-$preferential_money;
                            }else{
                                $pay_status = 2;
                                $pay_money = $all_now_pay_money;
                            }
                        }
                        $rowdata = [
                            'receiving_address' =>  $params['receiving_address'],
                            'number'            =>  $number,
                            'all_money'         =>  $all_money,
                            'tax_money'         =>  $tax_money,//税
                            'money_tax_price'   =>  $money_tax_price,//价税合计
                            'back_money'        =>  $back_money,//
    
                            'preferential_rate' =>  (float)$params['preferential_rate'],
                            'preferential_money'=>  (float)$params['preferential_money'],
                            'real_money'        =>  $all_money,//(float)$params['real_money'],
                            'purchase_money'    =>  (float)$params['costs'],
                            'note'              =>  $params['note'],
                            'buy_type'          =>  $params['buy_type'] ?? '',
                            'buy_version'       =>  $params['buy_version'] ?? '',
                            'serials'           =>  $params['serials'] ?? '',
                            'lock_code'         =>  $params['lock_code'] ?? '',
                            'receipt'           =>  $params['receipt'] ?? '',
    
                            'arrears'           =>  $all_money - $all_now_pay_money,//$params['arrears'],
                            'all_arrears'       =>  $params['add_arrears'],
    
                            'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                            'pay_money'         =>  isset($pay_money)?$pay_money:0,
                            'account'           =>  isset($pay_status)?$params['account']:0,
                            'cost_data'         =>  isset($params['cost_data'])?$params['cost_data']:null,
                            'goods_number'      =>  $goods_number,
                            'updatetime'        => time(),
                        ];
                    }
    
                    // if($this->model->where(['purchase_code'=>trim($params['purchase_code']),'id'=>['<>',$ids]])->find()){
                    //     $this->error('单据编号已占用');
                    // }
                    $info_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->column('id');
    
                    //附件记录开始
                    $enclosureLog = [];
                    if(isset($params['enclosure']) && !empty($params['enclosure'])){//选择了原始单据
                        $enclosure = explode(',',$params['enclosure']);
                        $enclosurelist = Db::name('kuerp_enclosure')->where(['id'=>['in',$params['enclosure']]])->select();
                        if(sizeof($enclosurelist)!=sizeof($enclosure)){
                            $this->error('选择的原始单据有误，请重新选择');
                        }else{
                            foreach ($enclosure as $k=>$v){
                                $enclosureLog[] = [
                                    'enclosure_id'  => $v,
                                    'purchase_code' => $params['purchase_code'],
                                    'type'          => '5',
                                ];
                            }
                        }
                        unset($params['enclosure']);
                    }
                    //附件记录结束
                    //核销单源单
                    $source_data = Db::name('kuerp_writeoff_source')->where(['purchase_type' => '3','type' => 1,'purchase_code'=>$row['purchase_code']])->find();

                    $result = false;
                    Db::startTrans();
                    try {
                        // if($examine!=1 && $row['examine_status']==1){
                        //     $this->examine($ids,2);
                        // }
    
                        //添加附件记录
                        Db::name('kuerp_enclosure_log')->where(['order_id'=>$ids,'type'=>'5'])->delete();
                        if(!empty($enclosureLog)){
                            foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                                $enclosureLog[$enclosureLog_k]['order_id'] = $ids;
                            }
                            Db::name('kuerp_enclosure_log')->insertAll($enclosureLog);
                        }
                        //添加附件记录结束
    
                        $result = $this->model->where(['id'=>$ids])->update($rowdata);
                        // if(!empty($info_id)){
                        //     Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
                        // }
                        //将锁号状态恢复，日志清除
                        if ($ischangeserial) {
                            $purchase_exchange_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$old_purchase_code])->column('id');
                            Db::name('kuerp_goods_serial')->where(['sale_id'=>['in',$purchase_exchange_id],'status'=>'3'])->update([
                                'status'=>'1',
                                'store_status'=>'1',
                                'sale_id' => 0,
                                'sale_code' => ''
                            ]);
                            Db::name('kuerp_goods_serial_log')->where(['business_type'=>'4','store_status'=>'2','purchase_code'=>$old_purchase_code])->delete();
                            if (!empty($serial_log)) {
                                Db::name('kuerp_goods_serial_log')->insertAll($serial_log);
                            }
                        }
    
                        //变更客户欠款信息
                        if ($params['arrears'] != $row['arrears']) {
                            $new_arrears = $params['arrears'] - $row['arrears'];
                            $new_arrears = $new_arrears < 0 ? 0 : $new_arrears;
                            Db::name('kuerp_customers')->where(['id'=>$row['customers_id']])->inc('need_receive_account',$new_arrears)->update();
                            //应收账款明细表修改
                            if ($params['arrears'] == 0) {
                                Db::name('kuerp_accounts_receivable')->where(['purchase_code'=>$row['purchase_code'], 'business_type' => '6'])->delete();
                            } else {
                                Db::name('kuerp_accounts_receivable')->where(['purchase_code'=>$row['purchase_code'], 'business_type' => '6'])->update([
                                    'receivable' => $rowdata['arrears'],
                                    'sale_money' => $rowdata['money_tax_price'],
                                    'receivable_money' => $rowdata['real_money'],
                                    'real_money' => $rowdata['pay_money'],
                                ]);
                            }
                            
                        }
                        //日志修改
                        if($rowdata['all_money'] != $row['all_money'] || $rowdata['back_money'] != $row['back_money']) {
                            //销货收款表修改
                            (new \app\admin\model\kuerp\SalesPaymentLog())->where(['bill_code'=>$row['purchase_code'], 'business_type' => '1'])->update([
                                'purchase_money' => $rowdata['all_money'],
                                'discount_money' => $rowdata['preferential_money'],
                                'real_money'     => $rowdata['real_money'],
                                'money_tax_price'=> $rowdata['money_tax_price'],
                                'give_money'     => $rowdata['arrears'],
                                'reamrk'         => $rowdata['note'],
                            ]);
                            //销货开票表修改
                            (new \app\admin\model\kuerp\SalesInvoicing())->where(['bill_code'=>$row['purchase_code']])->update([
                                'money'      => $rowdata['real_money'],
                                'real_money' => $rowdata['money_tax_price'],
                                'give_money' => $rowdata['arrears'],
                            ]);
                            Db::name('kuerp_goods_sales_profit')->where(['purchase_type' => '1','purchase_code'=>$row['purchase_code']])->update([
                                'all_money' => $rowdata['all_money'],
                                'money_tax_price' => $rowdata['money_tax_price'],
                                'real_money' => $rowdata['real_money'],
                                'need_money' => $rowdata['real_money'],
                                'remark' => $rowdata['note'],
                            ]);
                        }
                        //核销单源单
                        if (!$source_data) {
                            Db::name('kuerp_writeoff_source')->insertGetId([
                                'purchase_type' => 3,
                                'type' => 1,
                                'customers_id' => $row['customers_id'],
                                'purchase_code' => $row['purchase_code'],
                                'purchase_time' => $row['purchase_time'],
                                'price' => $rowdata['real_money'],
                                'money' => $rowdata['pay_money'],
                                'write_off' => $rowdata['arrears'],
                                'remark' => $rowdata['note'],
                            ]);
                        } else {
                            Db::name('kuerp_writeoff_source')->where(['purchase_type' => '3','type' => 1,'purchase_code'=>$row['purchase_code']])->update([
                                'price' => $rowdata['real_money'],
                                'money' => $rowdata['pay_money'],
                                'write_off' => $rowdata['arrears'],
                                'remark' => $rowdata['note'],
                            ]);
                        }
                        
                        if ($source_data) {
                            Db::name('kuerp_writeoff_log')->where(['source_id' => $source_data['id']])->update([
                                'write_off' => $rowdata['real_money'] - $rowdata['pay_money'],
                            ]);
                        }

                        foreach ($update_data as $data_k=>$data_v){
                            $goods_serial = $data_v['serial_code'];
                            unset($data_v['serial_code']);
                            if ($data_v['real_money'] != $all_money) {
                                $data_v['real_money'] = $all_money;
                            }
    
                            $goods_batch_info = $data_v['goods_batch_info'];
                            unset($data_v['goods_batch_info']);

                            $purchase_id = Db::name('kuerp_goods_sales_info')->where('id', $data_v['id'])->update($data_v);
    
                            //批次
                            if($goods_batch_info){
                                $goods_batch_info['purchase_info_id'] = $data_v['id'];
                                Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info);
                            }
    
                            if(!empty($goods_serial)){
                                Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
                                    'status'=>'3',
                                    'store_status'=>'2',
                                    'sale_id' => $data_v['id'],
                                    'sale_code' => $row['purchase_code']
                                ]);
                            }
    
                            // if(!empty($data_v['order_info_id'])){
                            //     Db::name('kuerp_goods_saleord_info')->insert([
                            //         'order_id'=>$data_v['order_info_id'],
                            //         'purchase_id'=>$purchase_id,
                            //         'number'=>$data_v['number'],
                            //         'money'=>$data_v['pay_money'],
                            //         'all_money'=>$data_v['all_money'],
                            //         'tax_rate'=>$data_v['tax_rate'],
                            //         'tax_money'=>$data_v['tax_money'],
                            //         'money_tax_price'=>$data_v['money_tax_price']
                            //     ]);
                            // }
                            //修改统计表
                            $summary_data = $data_v;
                            unset($summary_data['id']);
                            Db::name('kuerp_goods_sales_summary')->where(['purchase_code'=>$row['purchase_code'], 'salesinfoid' => $data_v['id']])->update($summary_data);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($result !== false) {
                        if($examine!=1){
                            try {
                                $exa = $this->examine($ids,1);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa) || $exa['status']!=1){
                                $this->error(__('No rows were inserted'));
                            }
                        }
                        $this->success();
                    } else {
                        $this->error(__('No rows were inserted'));
                    }
                } else {
                    $data = [];
                    $number = 0;$all_money = 0;$tax_money=0;$money_tax_price=0;
                    $back_money = 0;//返款金额
                    $goods_number = 0;//询价条数
                    foreach ($params['goods_code'] as $k=>$v){
                        if(!empty($v)){//有产品编号
                            $number+=$params['number'][$k];
                            //判断金额是否一致
                            $infototal = round((float)$params['number'][$k] * (float)$params['unit_price'][$k] - (float)$params['back_money'][$k], 2);
                            if($infototal!=$params['all_money'][$k]){
                                $params['all_money'][$k] = $infototal;
                                $params['money_tax_price'][$k] = $infototal;
                            }
                            $all_money+=$params['all_money'][$k];
                            $tax_money += (float)$params['tax_money'][$k];
                            $money_tax_price += (float)$params['money_tax_price'][$k];
                            $back_money += (float)$params['back_money'][$k];
    
                            if(!isset($params['stores_id'][$k]) || empty($params['stores_id'][$k])){
                                $this->error('请选择仓库');
                            }
    
                            unset($pay_money);unset($pay_status);
                            if($now_pay_money>0){
                                if($now_pay_money-$params['money_tax_price'][$k]>=0){
                                    $pay_status = 1;
                                    $pay_money = $params['money_tax_price'][$k];
                                    $now_pay_money -= $pay_money;
                                }else{
                                    $pay_status = 2;
                                    $pay_money = $now_pay_money;
                                    $now_pay_money -= $now_pay_money;
                                }
                            }
    
                            $goods = Db::name('kuerp_goods')->where(['goods_code'=>$v])->field('id,serial,batch,auxiliary')->find();
                            $batch_data = Db::name('kuerp_goods_batch')->where(['id'=>$params['batch_id'][$k]])->find();
                            if ($goods['auxiliary']==1 && empty($params['goods_attr'][$k]) && $auxiliary_status==1){
                                return ['status'=>500,'msg'=>'请选择商品'.$v.'属性'];
                            }

                            if(in_array($v,array_merge($this->goods_code_caijia,$this->goods_code_xunjia))){  //判断是否有材价通账号
                                if(empty($params['remark'][$k])){
                                    $this->error('请在商品'.$v.'{备注栏}里面输入续费的材价通手机号');
                                }
                                if(empty($params['goods_number'][$k]) && in_array($v,$this->goods_code_xunjia)){
                                    $this->error('商品'.$v.'未输入续费询价条数');
                                }
                                if(empty($params['year_number'][$k]) && in_array($v,$this->goods_code_caijia)){
                                    $this->error('商品'.$v.'未输入续费时长');
                                }
                                if(!empty($params['remark'][$k])){
                                    $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$params['remark'][$k]));
                                }
                                $caijiaUserModel = new \app\common\model\caijiatong\User();
                                foreach ($remark as $remark_mobile){
                                    $caijia_user = $caijiaUserModel->getUserInfo($remark_mobile);
                                    if(!$caijia_user){
                                        $this->error('材价通会员账号'.$remark_mobile.'不存在');
                                    }
                                }

                            }
                            if(in_array($v,$this->goods_code_wls)){  //判断网络锁是否存在
                                if(empty($params['remark'][$k])){
                                    $this->error('请在商品'.$v.'{备注栏}里面输入续费的网络锁锁内码');
                                }
                                if(empty($params['year_number'][$k])){
                                    $this->error('商品'.$v.'未输入续费时长');
                                }
                                if(!empty($params['remark'][$k])){
                                    $remark = explode(',',str_replace([',', '，', '、'], [',',',',','],$params['remark'][$k]));
                                }
                                $caijiaUserSoftwareModel = new \app\common\model\caijiatong\UserSoftware();
                                foreach ($remark as $remark_mobile){
                                    if (((string)$remark_mobile)[0] != '2' && substr((string)$remark_mobile, 0, 5) != 'NBGV0') {
                                        $this->error($remark_mobile.'不是网络锁');
                                    }
                                    $caijia_user = $caijiaUserSoftwareModel->getUsersoftwareInfo($remark_mobile);
                                    if(!$caijia_user){
                                        $this->error('网络锁'.$remark_mobile.'不存在');
                                    }
                                }
                            }

                            $goods_batch_info = [];
                            if($goods['batch']==1 && $batch==1){
                                if(empty($params['batch'][$k])){
                                    $this->error('请选择生产批次');
                                }
                                if(empty($batch_data)){
                                    $this->error('生产批次不存在');
                                }
                                $goods_batch_info = [
                                    'batch_id'    => isset($batch_data['id'])?$batch_data['id']:'',
                                    'goods_id'    => $goods['id'],
                                    'goods_code'  => $params['goods_code'][$k],
                                    'attribute_id'=>isset($params['goods_attr'][$k])?$params['goods_attr'][$k]:0,
                                    'goods_unit'  =>  (int)$params['goods_unit'][$k],
                                    'stores_id'   => $params['stores_id'][$k],
                                    'stock'       => (float)$params['number'][$k],
                                    'number'      => (float)$params['number'][$k],
                                    'batch_name'  => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                                    'manufacture' => strtotime($params['manufacture'][$k]),
                                    'guarantee'   => $params['guarantee'][$k],
                                    'validity'    => strtotime($params['validity'][$k]),
                                    'status'      => '0',
                                    'type'        => 2,
                                    'createtime'  => time(),
                                    'updatetime'  => time(),
                                ];
                            }
    
                            $serial_code = [];
                            if(isset($params['period_period'][$k]) && $goods['serial']==1 && $set==1){
                                //没有填锁编号
                                if(empty($params['period_period'][$k]) && empty($params['serials'])){
                                    $this->error('请输入锁编号或者点击数量栏选择序列号');
                                }
                                if (!empty($params['period_period'][$k])) {
                                    $period_period = unserialize($params['period_period'][$k]);
                                    foreach ($period_period as $period_period_k=>$period_period_v){
                                        $serial_code[] = $period_period_v['serial'];
                                    }
                                    $where = [];
                                    $where['serial'] = ['in',$serial_code];
                                    if(!empty($params['purchase_id'][$k])){
                                        $where['purchase_code'] = $params['purchase_id'][$k];
                                    }
                                    $goods_serial = Db::name('kuerp_goods_serial')->where($where)->column('serial');
                                    if(empty($goods_serial)){
                                        $this->error('商品序列号不存在');
                                    }
                                    foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                        if(!in_array($serial_code_v,$goods_serial)){
                                            $this->error($serial_code_v.'商品序列号不存在');
                                        }
                                    }
                                    $goods_serials = Db::name('kuerp_goods_serial')->where(['status'=>['in',[2,3]],'serial'=>['in',$serial_code],'sale_id'=>['not in',$info_id]])->column('serial');
                                    if(!empty($goods_serials)){
                                        $goods_serials = implode(',',$goods_serials);
                                        $this->error('商品序列号'.$goods_serials.'已经待出库，不可重复出库');
                                    }
                                }
                            }
    
                            if(!empty($params['info_id'][$k])){
                                $unit_id_order = Db::name('kuerp_goods_sales_order_info')->where(['id'=>$params['info_id'][$k]])->value('goods_unit');
                                if(!empty($unit_id_order) && $unit_id_order!=$params['goods_unit'][$k]){
                                    $this->error('选择的商品单位与源购货订单不一致，保存失败');
                                }
                            }

                            //时间期限
                            $start_date = $end_date = null;
                            if(!empty($params['date_range'][$k])){
                                $date_range = str_replace(' - ', ',', $params['date_range'][$k]);
                                $arr = array_slice(explode(',', $date_range), 0, 2);
                                $start_date = $arr[0];
                                $end_date = $arr[1];
                            }
                            //询价条数
                            $goods_number += !empty($params['goods_number'][$k]) ? (float)$params['goods_number'][$k] : 0;
    
                            $data[] = [
                                'purchase_code'     =>  $params['purchase_code'],
                                'purchase_type'     =>  $params['purchase_type'],
                                'purchase_time'     =>  strtotime($params['purchase_time']),
                                'customers_id'      =>  (int)$params['customers_id'],//客户
                                'sale_user'         =>  $sale_user,//销售员
                                'sale_user_name'    =>  $sale_user_name,//销售员名称
                                'receiving_address' =>  $params['receiving_address'],
    
                                'goods_code'        =>  $v,//商品信息
                                'goods_note'        =>  $params['goods_note'][$k],
                                'goods_unit'        =>  (int)$params['goods_unit'][$k],
                                'goods_type'        =>  $params['goods_type'][$k],
    
                                'stores_id'         =>  (int)$params['stores_id'][$k],
                                'allow_stock'       =>  (float)$params['allow_stock'][$k],
                                'order_info_id'     =>  (float)$params['info_id'][$k],
                                'number'            =>  (float)$params['number'][$k],
                                'default_unit'      =>  (float)$params['default_unit'][$k],
                                'basic_nmber'       =>  (float)$params['basic_nmber'][$k],
                                'unit_price'        =>  (float)$params['unit_price'][$k],
                                'cost_price'        =>  0,
                                'discount'          =>  (float)$params['discount'][$k],
                                'dis_money'         =>  (float)$params['dis_money'][$k],
                                'back_money'        =>  (float)$params['back_money'][$k],
                                'all_money'         =>  (float)$params['all_money'][$k],
                                'remark'            =>  $params['remark'][$k],
    
                                'goods_attr'        =>  (float)$params['goods_attr'][$k],
                                'tax_included'      =>  (float)$params['tax_included'][$k],
                                'tax_rate'          =>  (float)$params['tax_rate'][$k],
                                'tax_money'         =>  (float)$params['tax_money'][$k],
                                'money_tax_price'   =>  (float)$params['money_tax_price'][$k],
    
                                'batch_id'          => isset($batch_data['id'])?$batch_data['id']:'',
                                'batch_name'        => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                                'manufacture'       => strtotime($params['manufacture'][$k]),
                                'guarantee'         => $params['guarantee'][$k],
                                'validity'          => strtotime($params['validity'][$k]),
    
                                'preferential_rate' =>  (float)$params['preferential_rate'],
                                'preferential_money'=>  (float)$params['preferential_money'],
                                'real_money'        =>  (float)$params['real_money'],
                                'purchase_money'    =>  (float)$params['purchase_money'][$k],
                                'preparation_id'    =>  $admin['id'],
                                'operation_id'      =>  $admin['id'],
    
                                'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                                'pay_money'         =>  isset($pay_money)?$pay_money:0,
                                'account'           =>  isset($pay_status)?$params['account']:0,
    
                                'createtime'        => $row['createtime'],
                                'updatetime'        => time(),
                                'period'            =>  $params['period_period'][$k]===''?null:$params['period_period'][$k],
                                'serial_code'       => $serial_code,
                                'goods_batch_info'  => $goods_batch_info,
                                'start_date'        => $start_date,
                                'end_date'          => $end_date,
                                'year_number'      => !empty($params['year_number'][$k]) ? (float)$params['year_number'][$k] : 0,
                                'goods_number'      => !empty($params['goods_number'][$k]) ? (float)$params['goods_number'][$k] : 0,
                            ];
                        }
                    }
                    $preferential_money = (float)$params['preferential_money'];
                    if(!empty($data)){
                        if($all_now_pay_money>0){//当次支付金额
                            if($all_now_pay_money+$preferential_money-$money_tax_price>=0){
                                $pay_status = 1;
                                $pay_money = $money_tax_price-$preferential_money;
                            }else{
                                $pay_status = 2;
                                $pay_money = $all_now_pay_money;
                            }
                        }
                        $rowdata = [
                            'purchase_code'     =>  $params['purchase_code'],
                            'purchase_type'     =>  $params['purchase_type'],
                            'purchase_time'     =>  strtotime($params['purchase_time']),
                            'customers_id'      =>  (int)$params['customers_id'],//客户
                            'sale_user'         =>  $sale_user,//销售员
                            'sale_user_name'    =>  $sale_user_name,//销售员名称
                            'receiving_address' =>  $params['receiving_address'],
                            'customers_money'   =>  (float)$params['customers_money'],
    
                            'number'            =>  $number,
                            'all_money'         =>  $all_money,
    
                            'tax_money'         =>  $tax_money,//税
                            'money_tax_price'   =>  $money_tax_price,//价税合计
                            'back_money'        =>  $back_money,//
    
                            'preferential_rate' =>  (float)$params['preferential_rate'],
                            'preferential_money'=>  (float)$params['preferential_money'],
                            'real_money'        =>  $all_money,//(float)$params['real_money'],
                            'purchase_money'    =>  (float)$params['costs'],
                            'note'              =>  $params['note'],
                            'buy_type'          =>  $params['buy_type'] ?? '',
                            'buy_version'       =>  $params['buy_version'] ?? '',
                            'customers_users'   =>  $params['customers_users'] ?? '',
                            'serials'           =>  $params['serials'] ?? '',
                            'lock_code'         =>  $params['lock_code'] ?? '',
                            'receipt'           =>  $params['receipt'] ?? '',
                            // 'preparation_id'    =>  $admin['id'],
                            'operation_id'      =>  $admin['id'],
    
                            'arrears'           =>  $all_money - $all_now_pay_money,//$params['arrears'],
                            'all_arrears'       =>  $params['add_arrears'],
    
                            'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                            'pay_money'         =>  isset($pay_money)?$pay_money:0,
                            'account'           =>  isset($pay_status)?$params['account']:0,
                            'cost_data'         =>  isset($params['cost_data'])?$params['cost_data']:null,
                            'goods_number'      => $goods_number,
                            'updatetime'        => time(),
                        ];
                        if ($row['examine_status'] == 2) {
                            $rowdata['examine_status'] = 0;
                            $rowdata['examine_id'] = 0;
                            $rowdata['examine_time'] = 0;
                            $rowdata['examine_remark'] = '';
                        }
                        //是否在审核流程中
                        //获取审批流程
                        $flows = Db::name('flows')->where('relation_type', 'goods_sale')->where('status', 1)->find();
                        if (!empty($flows) && $row['preparation_id'] == $admin['id']){
                            $flows['flow_items'] = json_decode($flows['flow_items'], true);
                            //判断流程中是否有当前用户审核
                            $examine_index = 0;
                            foreach ($flows['flow_items'] as $key => $value) {
                                if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                                    $examine_index = $key + 1;
                                    // break;
                                }
                            }
                            if ($examine_index > 0) {
                                $rowdata['examine_id'] = $this->auth->id;
                                $rowdata['examine_adminids'] = $this->auth->id;
                                $rowdata['check_history_uids'] = $this->auth->id;
                                $rowdata['examine_index'] = $examine_index;
                            }
                        }
                    } else {
                        $this->error('请选择商品');
                    }
    
                    if($this->model->where(['purchase_code'=>trim($params['purchase_code']),'id'=>['<>',$ids]])->find()){
                        $this->error('单据编号已占用');
                    }
                    $info_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->column('id');
    
                    //附件记录开始
                    $enclosureLog = [];
                    if(isset($params['enclosure']) && !empty($params['enclosure'])){//选择了原始单据
                        $enclosure = explode(',',$params['enclosure']);
                        $enclosurelist = Db::name('kuerp_enclosure')->where(['id'=>['in',$params['enclosure']]])->select();
                        if(sizeof($enclosurelist)!=sizeof($enclosure)){
                            $this->error('选择的原始单据有误，请重新选择');
                        }else{
                            foreach ($enclosure as $k=>$v){
                                $enclosureLog[] = [
                                    'enclosure_id'  => $v,
                                    'purchase_code' => $params['purchase_code'],
                                    'type'          => '5',
                                ];
                            }
                        }
                        unset($params['enclosure']);
                    }
                    //附件记录结束
    
                    $result = false;
                    Db::startTrans();
                    try {
                        if($examine!=1 && $row['examine_status']==1){
                            $this->examine($ids,2);
                        }
    
                        //添加附件记录
                        Db::name('kuerp_enclosure_log')->where(['order_id'=>$ids,'type'=>'5'])->delete();
                        if(!empty($enclosureLog)){
                            foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                                $enclosureLog[$enclosureLog_k]['order_id'] = $ids;
                            }
                            Db::name('kuerp_enclosure_log')->insertAll($enclosureLog);
                        }
                        //添加附件记录结束
    
                        $result = $this->model->where(['id'=>$ids])->update($rowdata);
                        if(!empty($info_id)){
                            Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
                        }
    
                        $purchase_exchange_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$old_purchase_code])->column('id');
                        Db::name('kuerp_goods_serial')->where(['sale_id'=>['in',$purchase_exchange_id],'status'=>'3'])->update([
                            'status'=>'1',
                        ]);
                        Db::name('kuerp_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_exchange_id]])->delete();
    
                        Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->delete();
    
                        foreach ($data as $data_k=>$data_v){
                            $goods_serial = $data_v['serial_code'];
                            unset($data_v['serial_code']);
                            if ($data_v['real_money'] != $all_money) {
                                $data_v['real_money'] = $all_money;
                            }
    
                            $goods_batch_info = $data_v['goods_batch_info'];
                            unset($data_v['goods_batch_info']);
    
                            $purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v);
    
                            //批次
                            if($goods_batch_info){
                                $goods_batch_info['purchase_info_id'] = $purchase_id;
                                Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info);
                            }
    
                            if(!empty($goods_serial)){
                                Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
                                    'status'=>'3',
                                    'sale_id' => $purchase_id,
                                    'sale_code' => $data_v['purchase_code']
                                ]);
                            }
    
                            if(!empty($data_v['order_info_id'])){
                                Db::name('kuerp_goods_saleord_info')->insert([
                                    'order_id'=>$data_v['order_info_id'],
                                    'purchase_id'=>$purchase_id,
                                    'number'=>$data_v['number'],
                                    'money'=>$data_v['pay_money'],
                                    'all_money'=>$data_v['all_money'],
                                    'tax_rate'=>$data_v['tax_rate'],
                                    'tax_money'=>$data_v['tax_money'],
                                    'money_tax_price'=>$data_v['money_tax_price']
                                ]);
                            }
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($result !== false) {
                        if($examine!=1){
                            try {
                                $exa = $this->examine($ids,1);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa) || $exa['status']!=1){
                                $this->error(__('No rows were inserted'));
                            }
                        }
                        $this->success();
                    } else {
                        $this->error(__('No rows were inserted'));
                    }
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        $serials_arr = [];
        $purchase_info = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->select();
        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
            $purchase_info[$purchase_info_k]['serial'] = $purchase_info_v['period'];
            $purchase_info[$purchase_info_k]['date_range'] = !empty($purchase_info_v['start_date']) && !empty($purchase_info_v['end_date']) ? ($purchase_info_v['start_date'].' - '.$purchase_info_v['end_date']) : '';
            $purchase_info[$purchase_info_k]['unit'] = json_decode($this->getUnit($purchase_info_v['goods_code']),true);
            if ($purchase_info_v['period']) {
                $periods = unserialize($purchase_info_v['period']);
                foreach ($periods as $periods_k=>$periods_v){
                    $serials_arr[$purchase_info_v['goods_code'].'_'.($purchase_info_k+2)][] = $periods_v;
                }
            }
        }
        $this->view->assign("purchase_info", $purchase_info);
        $this->assignconfig("serials_arr", $serials_arr);

        $give_account = Db::name('kuerp_customers')->where(['id'=>$row['customers_id']])->value('need_receive_account');
        if($row['examine_status']==1){
            $this->assignconfig("give_account", $give_account-$row['arrears']);
            $this->view->assign("give_account", (float)$give_account);
        }else{
            $this->assignconfig("give_account", $give_account);
            $this->view->assign("give_account", (float)$give_account+$row['arrears']);
        }

        //查询原始单据
        $enclosure_id = Db::name('kuerp_enclosure_log')->where(['order_id'=>$ids,'type'=>'5'])->column('enclosure_id');
        if(!empty($enclosure_id)){
            $this->assign('enclosure_count',sizeof($enclosure_id));
            $enclosure_id = implode(',',$enclosure_id);
        }else{
            $enclosure_id = '';
        }
        $this->assign('enclosure_ids',$enclosure_id);

        //审核禁止输入
        $examine_set= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');
        if($examine_set==1 && $row['examine_status']==1){
            $this->assign('exclass','hiddens');
        }
        //审核中禁止输入
        if ($row['examine_status'] == 0) {
            if ($row['examine_index'] > 0 || $row['examine_adminids'] != '') {
                $row['examine_status'] = 3;
            }
        }
        $this->assignconfig("examine_status", $row['examine_status']);
        $this->assignconfig("suppliersList", $this->model->getSuppliersList());
        $this->assignconfig("expendTypeList", $this->model->getExpendTypeList());
        $stores_id = '';
        if ($this->auth->is_sale) {
            $stores_id = $this->auth->stores_info['id'] ?? '';
        }
        $this->assignconfig("stores_id", $stores_id);
        

        //获取审核信息
        $logWhere = [
            'relation_type' => 'goods_sale',
            'relation_id' => $ids,
        ];
        $logList = Db::name('examine_log')->where($logWhere)->order('id desc')->select();
        if (!empty($logList)) {
            $admin_ids = array_column($logList,'admin_id');
            $admin_data = Db::name('admin')->where(['id'=>['in',$admin_ids]])->column('nickname,username,avatar','id');
            foreach ($logList as $log_k=>$log_v) {
                $logList[$log_k]['admin_name'] = $admin_data[$log_v['admin_id']]['nickname'] ?? $admin_data[$log_v['admin_id']]['username'] ?? '';
                $logList[$log_k]['admin_avatar'] = $admin_data[$log_v['admin_id']]['avatar'] ?? '';
                $logList[$log_k]['createtime'] = date('Y/m/d H:i', $log_v['createtime']);
            }
        }
        
        $this->assign('log_list',$logList);
        //是否可审核后编辑
        $this->assignconfig("enableEdit", $enableEdit);
        $this->assign("enableEdit", $enableEdit);

        if ($row['examine_status']==1) {
            $goodslist = (new GoodsModel())->select();
            $this->view->assign("goodsList", $goodslist);
            $this->assignconfig("goodsList", $goodslist);
        }
        

        return $this->view->fetch();
    }

    public function edit1($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $examine= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');
            if($row['examine_status']==1 && $examine==1){
                $this->error('不能编辑已审核的数据');
            }
            if($row['check_status']==1){
                $this->error('不能编辑已对单的数据');
            }
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $old_purchase_code = $params['old_purchase_code'];unset($params['old_purchase_code']);
                $info_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$old_purchase_code])->column('id');

                if(empty($params['purchase_code'])){
                    $this->error('请填写单据编号');
                }

                $admin = Session::get('admin');
                if($params['now_pay_money']>0){
                    if(empty($params['account'])){
                        $this->error('请选择结算账户');
                    }
                    $all_now_pay_money = $now_pay_money = trim($params['now_pay_money']);
                }else{
                    $all_now_pay_money = $now_pay_money = 0;
                }

                $set= Db::name('kuerp_sets')->where(['name'=>'serial'])->value('is_checked');
                $batch= Db::name('kuerp_sets')->where(['name'=>'batch'])->value('is_checked');
                $auxiliary_status= Db::name('kuerp_sets')->where(['name'=>'auxiliary'])->value('is_checked');
                //销售员 当前登录为销售员时
                $saleList = $this->model->getSaleList($this->auth->staff_member_id ?? 0);
                $sale_user = (int)$params['sale_user'];
                $sale_user_name = '';
                if ($this->auth->is_sale) {
                    $sale_user = $this->auth->staff_member_id;
                }
                if(!empty($sale_user)){
                    foreach ($saleList as $sale_k=>$sale_v) {
                        if ($sale_user == $sale_v['id']) {
                            $sale_user_name = $sale_v['name'];
                            break;
                        }
                    }
                }
                $data = [];
                $number = 0;$all_money = 0;$tax_money=0;$money_tax_price=0;
                $back_money = 0;//返款金额
                foreach ($params['goods_code'] as $k=>$v){
                    if(!empty($v)){//有产品编号
                        $number+=$params['number'][$k];
                        $all_money+=$params['all_money'][$k];
                        $tax_money += (float)$params['tax_money'][$k];
                        $money_tax_price += (float)$params['money_tax_price'][$k];
                        $back_money += (float)$params['back_money'][$k];

                        if(!isset($params['stores_id'][$k]) || empty($params['stores_id'][$k])){
                            $this->error('请选择仓库');
                        }

                        unset($pay_money);unset($pay_status);
                        if($now_pay_money>0){
                            if($now_pay_money-$params['money_tax_price'][$k]>=0){
                                $pay_status = 1;
                                $pay_money = $params['money_tax_price'][$k];
                                $now_pay_money -= $pay_money;
                            }else{
                                $pay_status = 2;
                                $pay_money = $now_pay_money;
                                $now_pay_money -= $now_pay_money;
                            }
                        }

                        $goods = Db::name('kuerp_goods')->where(['goods_code'=>$v])->field('id,serial,batch,auxiliary')->find();
                        $batch_data = Db::name('kuerp_goods_batch')->where(['id'=>$params['batch_id'][$k]])->find();
                        if ($goods['auxiliary']==1 && empty($params['goods_attr'][$k]) && $auxiliary_status==1){
                            return ['status'=>500,'msg'=>'请选择商品'.$v.'属性'];
                        }
                        $goods_batch_info = [];
                        if($goods['batch']==1 && $batch==1){
                            if(empty($params['batch'][$k])){
                                $this->error('请选择生产批次');
                            }
                            if(empty($batch_data)){
                                $this->error('生产批次不存在');
                            }
                            $goods_batch_info = [
                                'batch_id'    => isset($batch_data['id'])?$batch_data['id']:'',
                                'goods_id'    => $goods['id'],
                                'goods_code'  => $params['goods_code'][$k],
                                'attribute_id'=>isset($params['goods_attr'][$k])?$params['goods_attr'][$k]:0,
                                'goods_unit'  =>  (int)$params['goods_unit'][$k],
                                'stores_id'   => $params['stores_id'][$k],
                                'stock'       => (float)$params['number'][$k],
                                'number'      => (float)$params['number'][$k],
                                'batch_name'  => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                                'manufacture' => strtotime($params['manufacture'][$k]),
                                'guarantee'   => $params['guarantee'][$k],
                                'validity'    => strtotime($params['validity'][$k]),
                                'status'      => '0',
                                'type'        => 2,
                                'createtime'  => time(),
                                'updatetime'  => time(),
                            ];
                        }

                        $serial_code = [];
                        if(isset($params['period_period'][$k]) && $goods['serial']==1 && $set==1){
                            //没有填锁编号
                            if(empty($params['period_period'][$k]) && empty($params['serials'])){
                                $this->error('请输入锁编号或者点击数量栏选择序列号');
                            }
                            if (!empty($params['period_period'][$k])) {
                                $period_period = unserialize($params['period_period'][$k]);
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    $serial_code[] = $period_period_v['serial'];
                                }
                                $where = [];
                                $where['serial'] = ['in',$serial_code];
                                if(!empty($params['purchase_id'][$k])){
                                    $where['purchase_code'] = $params['purchase_id'][$k];
                                }
                                $goods_serial = Db::name('kuerp_goods_serial')->where($where)->column('serial');
                                if(empty($goods_serial)){
                                    $this->error('商品序列号不存在');
                                }
                                foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                    if(!in_array($serial_code_v,$goods_serial)){
                                        $this->error($serial_code_v.'商品序列号不存在');
                                    }
                                }
                                $goods_serials = Db::name('kuerp_goods_serial')->where(['status'=>['in',[2,3]],'serial'=>['in',$serial_code],'purchase_exchange_id'=>['not in',$info_id]])->column('serial');
                                if(!empty($goods_serials)){
                                    $goods_serials = implode(',',$goods_serials);
                                    $this->error('商品序列号'.$goods_serials.'已经待出库，不可重复出库');
                                }
                            }
                        }

                        if(!empty($params['info_id'][$k])){
                            $unit_id_order = Db::name('kuerp_goods_sales_order_info')->where(['id'=>$params['info_id'][$k]])->value('goods_unit');
                            if(!empty($unit_id_order) && $unit_id_order!=$params['goods_unit'][$k]){
                                $this->error('选择的商品单位与源购货订单不一致，保存失败');
                            }
                        }

                        $data[] = [
                            'purchase_code'     =>  $params['purchase_code'],
                            'purchase_type'     =>  $params['purchase_type'],
                            'purchase_time'     =>  strtotime($params['purchase_time']),
                            'customers_id'      =>  (int)$params['customers_id'],//客户
                            'sale_user'         =>  $sale_user,//销售员
                            'sale_user_name'    =>  $sale_user_name,//销售员名称
                            'receiving_address' =>  $params['receiving_address'],

                            'goods_code'        =>  $v,//商品信息
                            'goods_note'        =>  $params['goods_note'][$k],
                            'goods_unit'        =>  (int)$params['goods_unit'][$k],
                            'goods_type'        =>  $params['goods_type'][$k],

                            'stores_id'         =>  (int)$params['stores_id'][$k],
                            'allow_stock'       =>  (float)$params['allow_stock'][$k],
                            'order_info_id'     =>  (float)$params['info_id'][$k],
                            'number'            =>  (float)$params['number'][$k],
                            'default_unit'      =>  (float)$params['default_unit'][$k],
                            'basic_nmber'       =>  (float)$params['basic_nmber'][$k],
                            'unit_price'        =>  (float)$params['unit_price'][$k],
                            'cost_price'        =>  0,
                            'discount'          =>  (float)$params['discount'][$k],
                            'dis_money'         =>  (float)$params['dis_money'][$k],
                            'back_money'        =>  (float)$params['back_money'][$k],
                            'all_money'         =>  (float)$params['all_money'][$k],
                            'remark'            =>  $params['remark'][$k],

                            'goods_attr'        =>  (float)$params['goods_attr'][$k],
                            'tax_included'      =>  (float)$params['tax_included'][$k],
                            'tax_rate'          =>  (float)$params['tax_rate'][$k],
                            'tax_money'         =>  (float)$params['tax_money'][$k],
                            'money_tax_price'   =>  (float)$params['money_tax_price'][$k],

                            'batch_id'          => isset($batch_data['id'])?$batch_data['id']:'',
                            'batch_name'        => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                            'manufacture'       => strtotime($params['manufacture'][$k]),
                            'guarantee'         => $params['guarantee'][$k],
                            'validity'          => strtotime($params['validity'][$k]),

                            'preferential_rate' =>  (float)$params['preferential_rate'],
                            'preferential_money'=>  (float)$params['preferential_money'],
                            'real_money'        =>  (float)$params['real_money'],
                            'purchase_money'    =>  (float)$params['purchase_money'][$k],
                            'preparation_id'    =>  $admin['id'],
                            'operation_id'      =>  $admin['id'],

                            'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                            'pay_money'         =>  isset($pay_money)?$pay_money:0,
                            'account'           =>  isset($pay_status)?$params['account']:0,

                            'createtime'        => $row['createtime'],
                            'updatetime'        => time(),
                            'period'            =>  $params['period_period'][$k]===''?null:$params['period_period'][$k],
                            'serial_code'       => $serial_code,
                            'goods_batch_info'  => $goods_batch_info,
                        ];
                    }
                }
                $preferential_money = (float)$params['preferential_money'];
                if(!empty($data)){
                    if($all_now_pay_money>0){//当次支付金额
                        if($all_now_pay_money+$preferential_money-$money_tax_price>=0){
                            $pay_status = 1;
                            $pay_money = $money_tax_price-$preferential_money;
                        }else{
                            $pay_status = 2;
                            $pay_money = $all_now_pay_money;
                        }
                    }
                    $rowdata = [
                        'purchase_code'     =>  $params['purchase_code'],
                        'purchase_type'     =>  $params['purchase_type'],
                        'purchase_time'     =>  strtotime($params['purchase_time']),
                        'customers_id'      =>  (int)$params['customers_id'],//客户
                        'sale_user'         =>  $sale_user,//销售员
                        'sale_user_name'    =>  $sale_user_name,//销售员名称
                        'receiving_address' =>  $params['receiving_address'],
                        'customers_money'   =>  (float)$params['customers_money'],

                        'number'            =>  $number,
                        'all_money'         =>  $all_money,

                        'tax_money'         =>  $tax_money,//税
                        'money_tax_price'   =>  $money_tax_price,//价税合计
                        'back_money'        =>  $back_money,//

                        'preferential_rate' =>  (float)$params['preferential_rate'],
                        'preferential_money'=>  (float)$params['preferential_money'],
                        'real_money'        =>  (float)$params['real_money'],
                        'purchase_money'    =>  (float)$params['costs'],
                        'note'              =>  $params['note'],
                        'buy_type'          =>  $params['buy_type'] ?? '',
                        'buy_version'       =>  $params['buy_version'] ?? '',
                        'customers_users'   =>  $params['customers_users'] ?? '',
                        'serials'           =>  $params['serials'] ?? '',
                        'lock_code'         =>  $params['lock_code'] ?? '',
                        'preparation_id'    =>  $admin['id'],
                        'operation_id'      =>  $admin['id'],

                        'arrears'           =>  $params['arrears'],
                        'all_arrears'       =>  $params['add_arrears'],

                        'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                        'pay_money'         =>  isset($pay_money)?$pay_money:0,
                        'account'           =>  isset($pay_status)?$params['account']:0,
                        'cost_data'         =>  isset($params['cost_data'])?$params['cost_data']:null,
                        'updatetime'        => time(),
                    ];
                    if ($row['examine_status'] == 2) {
                        $rowdata['examine_status'] = 0;
                        $rowdata['examine_id'] = 0;
                        $rowdata['examine_time'] = 0;
                        $rowdata['examine_remark'] = '';
                    }
                } else {
                    $this->error('请选择商品');
                }

                if($this->model->where(['purchase_code'=>trim($params['purchase_code']),'id'=>['<>',$ids]])->find()){
                    $this->error('单据编号已占用');
                }
                $info_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->column('id');

                //附件记录开始
                $enclosureLog = [];
                if(isset($params['enclosure']) && !empty($params['enclosure'])){//选择了原始单据
                    $enclosure = explode(',',$params['enclosure']);
                    $enclosurelist = Db::name('kuerp_enclosure')->where(['id'=>['in',$params['enclosure']]])->select();
                    if(sizeof($enclosurelist)!=sizeof($enclosure)){
                        $this->error('选择的原始单据有误，请重新选择');
                    }else{
                        foreach ($enclosure as $k=>$v){
                            $enclosureLog[] = [
                                'enclosure_id'  => $v,
                                'purchase_code' => $params['purchase_code'],
                                'type'          => '5',
                            ];
                        }
                    }
                    unset($params['enclosure']);
                }
                //附件记录结束

                $result = false;
                Db::startTrans();
                try {
                    if($examine!=1 && $row['examine_status']==1){
                        $this->examine($ids,2);
                    }

                    //添加附件记录
                    Db::name('kuerp_enclosure_log')->where(['order_id'=>$ids,'type'=>'5'])->delete();
                    if(!empty($enclosureLog)){
                        foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                            $enclosureLog[$enclosureLog_k]['order_id'] = $ids;
                        }
                        Db::name('kuerp_enclosure_log')->insertAll($enclosureLog);
                    }
                    //添加附件记录结束

                    $result = $this->model->where(['id'=>$ids])->update($rowdata);
                    if(!empty($info_id)){
                        Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
                    }

                    $purchase_exchange_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$old_purchase_code])->column('id');
                    Db::name('kuerp_goods_serial')->where(['sale_id'=>['in',$purchase_exchange_id],'status'=>'3'])->update([
                        'status'=>'1',
                    ]);
                    Db::name('kuerp_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_exchange_id]])->delete();

                    Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->delete();

                    foreach ($data as $data_k=>$data_v){
                        $goods_serial = $data_v['serial_code'];
                        unset($data_v['serial_code']);

                        $goods_batch_info = $data_v['goods_batch_info'];
                        unset($data_v['goods_batch_info']);

                        $purchase_id = Db::name('kuerp_goods_sales_info')->insertGetId($data_v);

                        //批次
                        if($goods_batch_info){
                            $goods_batch_info['purchase_info_id'] = $purchase_id;
                            Db::name('kuerp_goods_batch_sale_info')->insert($goods_batch_info);
                        }

                        if(!empty($goods_serial)){
                            Db::name('kuerp_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
                                'status'=>'3',
                                'sale_id' => $purchase_id,
                                'sale_code' => $data_v['purchase_code']
                            ]);
                        }

                        if(!empty($data_v['order_info_id'])){
                            Db::name('kuerp_goods_saleord_info')->insert([
                                'order_id'=>$data_v['order_info_id'],
                                'purchase_id'=>$purchase_id,
                                'number'=>$data_v['number'],
                                'money'=>$data_v['pay_money'],
                                'all_money'=>$data_v['all_money'],
                                'tax_rate'=>$data_v['tax_rate'],
                                'tax_money'=>$data_v['tax_money'],
                                'money_tax_price'=>$data_v['money_tax_price']
                            ]);
                        }
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($examine!=1){
                        try {
                            $exa = $this->examine($ids,1);
                        } catch (Exception $e) {
                        }
                        if(!isset($exa) || $exa['status']!=1){
                            $this->error(__('No rows were inserted'));
                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        $purchase_info = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->select();
        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
            $purchase_info[$purchase_info_k]['serial'] = $purchase_info_v['period'];
            $purchase_info[$purchase_info_k]['unit'] = json_decode($this->getUnit($purchase_info_v['goods_code']),true);
        }
        $this->view->assign("purchase_info", $purchase_info);

        $give_account = Db::name('kuerp_customers')->where(['id'=>$row['customers_id']])->value('need_receive_account');
        if($row['examine_status']==1){
            $this->assignconfig("give_account", $give_account-$row['arrears']);
            $this->view->assign("give_account", (float)$give_account);
        }else{
            $this->assignconfig("give_account", $give_account);
            $this->view->assign("give_account", (float)$give_account+$row['arrears']);
        }

        //查询原始单据
        $enclosure_id = Db::name('kuerp_enclosure_log')->where(['order_id'=>$ids,'type'=>'5'])->column('enclosure_id');
        if(!empty($enclosure_id)){
            $this->assign('enclosure_count',sizeof($enclosure_id));
            $enclosure_id = implode(',',$enclosure_id);
        }else{
            $enclosure_id = '';
        }
        $this->assign('enclosure_ids',$enclosure_id);

        //审核禁止输入
        $examine_set= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');
        if($examine_set==1 && $row['examine_status']==1){
            $this->assign('exclass','hiddens');
        }
        //审核中禁止输入
        if ($row['examine_status'] == 0) {
            if ($row['examine_index'] > 0 || $row['examine_adminids'] != '') {
                $row['examine_status'] = 3;
            }
        }
        $this->assignconfig("examine_status", $row['examine_status']);
        $this->assignconfig("suppliersList", $this->model->getSuppliersList());
        $this->assignconfig("expendTypeList", $this->model->getExpendTypeList());
        $stores_id = '';
        if ($this->auth->is_sale) {
            $stores_id = $this->auth->stores_info['id'] ?? '';
        }
        $this->assignconfig("stores_id", $stores_id);

        //获取审核信息
        $logWhere = [
            'relation_type' => 'goods_sale',
            'relation_id' => $ids,
        ];
        $logList = Db::name('examine_log')->where($logWhere)->order('id desc')->select();
        if (!empty($logList)) {
            $admin_ids = array_column($logList,'admin_id');
            $admin_data = Db::name('admin')->where(['id'=>['in',$admin_ids]])->column('nickname,username,avatar','id');
            foreach ($logList as $log_k=>$log_v) {
                $logList[$log_k]['admin_name'] = $admin_data[$log_v['admin_id']]['nickname'] ?? $admin_data[$log_v['admin_id']]['username'] ?? '';
                $logList[$log_k]['admin_avatar'] = $admin_data[$log_v['admin_id']]['avatar'] ?? '';
                $logList[$log_k]['createtime'] = date('Y/m/d H:i', $log_v['createtime']);
            }
        }
        
        $this->assign('log_list',$logList);

        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            $examine= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $goods_purchase_id = [];$goods_purchase_code = [];
            foreach ($list as $list_k=>$list_v){
                if($list_v['check_status']==1){
                    $this->error('不能删除已对单的数据');
                }
                if($list_v['examine_status']==1 && $examine==1){
                    // $this->error('不能删除已审核的数据');
                    try {
                        $this->examine($list_v['id'],2);
                    } catch (Exception $e) {
                    }
                }elseif ($list_v['examine_status']==1 && $examine!=1){
                    try {
                        $this->examine($list_v['id'],2);
                    } catch (Exception $e) {
                    }
                }
                if(!in_array($list_v['id'],$goods_purchase_id)){
                    $goods_purchase_id[] = $list_v['id'];
                }
                if(!in_array($list_v['purchase_code'],$goods_purchase_code)){
                    $goods_purchase_code[] = $list_v['purchase_code'];
                }
            }
            $goods_purchase_info = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>['in',$goods_purchase_code]])->column('id');
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    $exchange_info = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$v['purchase_code']])->column('id');
                    Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$v['purchase_code']])->delete();
                    Db::name('kuerp_goods_serial')->where(['sale_id'=>['in',$exchange_info]])->update(['status'=>'8', 'store_status' => 1]);
                }
                Db::name('kuerp_goods_sales_summary')->where(['purchase_code'=>['in',$goods_purchase_code]])->delete();
                if(!empty($goods_purchase_id)){//销货订单关联
                    Db::name('kuerp_goods_saleord')->where(['purchase_id'=>['in',$goods_purchase_id]])->delete();
                    Db::name('kuerp_goods_batch_sale_info')->where(['purchase_id'=>['in',$goods_purchase_id]])->delete();
                }
                if(!empty($goods_purchase_info)){//销货订单详情关联
                    Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$goods_purchase_info]])->delete();
                }

                //删除附件记录
                Db::name('kuerp_enclosure_log')->where(['purchase_code'=>$v['purchase_code'],'type'=>'5'])->delete();
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //对单/反对单
    public function counter($ids = null,$counter=1){
        if($counter==1){
            $list = $this->model->where(['id'=>['in',$ids],'check_status'=>'0'])->select();
            foreach ($list as $list_k=>$list_v){
                (new \app\admin\controller\kuerp\Checkout())->checkOutTime($list_v['purchase_time']);
            }
            if(empty($list)){
                $this->error('请选择需要对单的数据');
            }
            $admin = Session::get('admin');
            Db::startTrans();
            try {
                $result = $this->model->where(['id'=>['in',$ids],'check_status'=>'0'])->update(['check_status'=>1,'operation_id'=>$admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                $this->success(sizeof($list).'条数据对单成功');
            }else{
                $this->error('对单失败');
            }
        }else{
            $list = $this->model->where(['id'=>['in',$ids],'check_status'=>'1'])->select();
            foreach ($list as $list_k=>$list_v){
                (new \app\admin\controller\kuerp\Checkout())->checkOutTime($list_v['purchase_time']);
            }
            if(empty($list)){
                $this->error('请选择需要反对单的数据');
            }
            $admin = Session::get('admin');
            Db::startTrans();
            try {
                $result = $this->model->where(['id'=>['in',$ids],'check_status'=>'1'])->update(['check_status'=>'0','operation_id'=>$admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                $this->success(sizeof($list).'条数据反对单成功');
            }else{
                $this->error('反对单失败');
            }
        }
    }

    //审核/反审核
    public function examine($ids = null,$examine=1){
        $examine_set= Db::name('kuerp_sets')->where(['name'=>'examine'])->value('is_checked');
        if(empty($ids)){
            if($examine_set!=1){
                return ['status'=>0,'msg'=>'系统错误'];
            }
            $this->error('请选择要操作的数据');
        }
        if($examine==1){
            $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])->select();
            $set_discount = \think\Db::name('kuerp_sets')->where(['name'=>'discount'])->value('is_checked');

            foreach ($list as $list_k=>$list_v){
                if($list_v['check_status']==1){
                    $this->error('不能反审核已对单的数据');
                }
            }
            $purchase_code = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])->column('purchase_code');
            if(empty($list)){
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>'系统错误'];
                }
                $this->error('请选择需要审核的数据');
            }
            $account_list_obj = Db::name('kuerp_accounts')->field('id,account_coding,account_name,balance')->select();
            $account_list = [];
            foreach ($account_list_obj as $account_list_obj_k=>$account_list_obj_v){
                $account_list[$account_list_obj_v['id']] = $account_list_obj_v;
            }
            $examine_ids = [];
            $accountData = [];
            $arrears = [];
            $log = [];
            $payment_log = [];$invoicing = [];
            foreach ($list as $list_k=>$list_v){
                $examine_ids[] = $list_v['id'];
                if($list_v['arrears']>0){
                    $suppliers = Db::name('kuerp_customers')->where(['id'=>$list_v['customers_id']])->field('id,need_receive_account')->find();
                    if($suppliers){
                        $status = false;
                        foreach ($arrears as $arrears_k=>$arrears_v){
                            if($arrears_v['id']==$suppliers['id']){
                                $arrears[$arrears_k]['need_receive_account'] = $list_v['arrears']+$arrears_v['need_receive_account'];
                                $status = true;
                            }
                        }
                        if(!$status){
                            $arrears[] = [
                                'id'  => $suppliers['id'],
                                'need_receive_account'  => $list_v['arrears']+$suppliers['need_receive_account'],
                            ];
                        }
                    }
                }
                if($list_v['pay_money']>0){
                    $accountData[] = [
                        'balance'  => $list_v['pay_money'],
                        'account'  => $list_v['account'],
                    ];
                    $log[] = [
                        'account_coding'    => $account_list[$list_v['account']]['account_coding'],
                        'account_name'      => $account_list[$list_v['account']]['account_name'],
                        'balance'           => $account_list[$list_v['account']]['balance']-$list_v['pay_money'],
                        'income'            => $list_v['pay_money'],
                        'pay_time'          => $list_v['purchase_time'],
                        'bill_code'         => $list_v['purchase_code'],
                        'business_type'     => 5,
                        'customers_id'      => $list_v['customers_id'],
                        'remark'            => $list_v['note'],
                        'createtime'        => time(),
                        'updatetime'        => time(),
                    ];
                }
                $payment_log[] = [
                    'customers_id'   => $list_v['customers_id'],
                    'sale_user'      => $list_v['sale_user'],
                    'sale_user_name' => $list_v['sale_user_name'] ?? '',
                    'business_type'  => 1,
                    'bill_time'      => $list_v['purchase_time'],
                    'bill_code'      => $list_v['purchase_code'],
                    'bill_codes'     => $list_v['purchase_code'],
                    'purchase_money' => $list_v['all_money'],
                    'discount_money' => $list_v['preferential_money'],
                    'real_money'     => $list_v['real_money'],
                    'money_tax_price'=> $list_v['money_tax_price'],
                    'pay_money'      => $list_v['pay_money'],
                    'give_money'     => $list_v['arrears'],
                    'reamrk'         => $list_v['note'],
                    'createtime'     => time(),
                ];
                if($set_discount==1){
                    $money = $list_v['real_money'];
                }else{
                    $money = $list_v['money_tax_price'];
                }
                $invoicing[] = [
                    'customers_id'   => $list_v['customers_id'],
                    'status'         => $list_v['pay_status'],
                    'bill_time'      => $list_v['purchase_time'],
                    'bill_code'      => $list_v['purchase_code'],
                    'bill_codes'     => $list_v['purchase_code'],
                    'money'          => $list_v['real_money'],
                    'tax'            => $list_v['tax_money'],
                    'real_money'     => $money,
                    'pay_money'      => 0,
                    'give_money'     => $money,
                    'createtime'     => time(),
                ];
            }
            $editstock = [];$addstock = [];$goods_stock = [];
            $info_list = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>['in',$purchase_code]])->select();
            //注释20241011
            // foreach ($info_list as $info_list_k=>$info_list_v){
            //     try {
            //         unset($info_list[$info_list_k]['period']);
            //     } catch (Exception $e) {
            //     }
            // }

            $purchase_info_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>['in',$purchase_code]])->column('id');

            $purchase_info = [];
            $goods_stock_log = [];//收发详情
            $serial_log = [];//序列号跟踪
            foreach ($info_list as $list_k=>$list_v){
                //序列号跟踪
                $goods_serial = Db::name('kuerp_goods_serial')->where((new Goods())->setWhere(['sale_id'=>$list_v['id']]))->field('goods_id,serial,stores_id,attribute_id')->select();
                foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                    $serial_log[] = (new Goods())->setDataInfo([
                        'goods_id'=>$goods_serial_v['goods_id'],
                        'stores_id'=>$goods_serial_v['stores_id'],
                        'attribute_id'=>$goods_serial_v['attribute_id'],
                        'serial'=>$goods_serial_v['serial'],
                        'business_type'=>'4',
                        'store_status'=>'2',
                        'remarks' => $list_v['remark'],
                        'purchase_id'=>$list_v['id'],
                        'customer_id'=>$list_v['customers_id'],
                        'purchase_code'=>$list_v['purchase_code'],
                        'purchase_time' => $list_v['purchase_time'],
                        'createtime'  => time(),
                        'updatetime'  => time(),
                    ]);
                }
                //序列号跟踪

                $info_list[$list_k]['sales_order_id']    = $list_v['id'];
                $info_list[$list_k]['createtime']        = time();
                $info_list[$list_k]['updatetime']        = time();
                $stock_number = $list_v['basic_nmber'];
                $goods = Db::name('kuerp_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,unit_id')->find();
                $status = false;
                foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                    if($goods_stock_v['id']==$goods['id']){
                        $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']-$stock_number;
                        $status = true;
                    }
                }
                if(!$status){
                    $goods_stock[] = [
                        'id'=>$goods['id'],
                        'inventory'=>$goods['inventory']-$stock_number,
                    ];
                }
                //商品库存
                $where = [];
                $where['goods_code'] = $list_v['goods_code'];
                $where['stores_id'] = $list_v['stores_id'];
                if($list_v['goods_attr']>0){
                    $goods_attr = $list_v['goods_attr'];
                    if($goods_attr>0){
                        $where['attribute_id'] = $goods_attr;
                    }
                }

                //获取成本单价
                $balance_cost=0;$balance_unit=0;
                $goodsInfo = json_decode((new GoodsPurchase())->getUnit($list_v['goods_code'],$list_v['stores_id'],$list_v['goods_attr']),true);
                $unitData = isset($goodsInfo['unit'])?$goodsInfo['unit']:[];
                if(empty($unitData)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>'商品信息获取错误'];
                    }
                    $this->error('商品信息获取错误');
                }else{
                    foreach ($unitData as $unitData_k=>$unitData_v){
                        if($unitData_v['id']==$goods['unit_id']){
                            $balance_unit = $unitData_v['purchase'];
                        }
                    }
                }
                //获取成本单价结束

                $stock = Db::name('kuerp_goods_stock')->where($where)->field('stock,id')->find();
                if($stock){
                    $status = false;
                    foreach ($editstock as $editstock_k=>$editstock_v){
                        if($editstock_v['id']==$stock['id']){
                            $editstock[$editstock_k]['stock'] -= $stock_number;
                            $status = true;
                            $balance_cost   = (round($balance_unit*$stock_number,4));
                        }
                    }
                    if(!$status){
                        $editstock[] = [
                            'id'=>$stock['id'],
                            'stock'=>(round($stock['stock']-$stock_number,4))
                        ];
                        $balance_cost   = (round($balance_unit*$stock_number,4));
                    }
                }else{
                    $store = Db::name('kuerp_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>'商品'.$store.'库存不足'];
                    }
                    $this->error('商品'.$store.'库存不足');
                }
                $purchase_info[] = $list_v['id'];

                //收发详情
                if($goods){
                    $goods_stock_log[] = (new Goods())->setDataInfo([
                        'purchase_code' => $list_v['purchase_code'],
                        'purchase_id'   => $list_v['id'],
                        'purchase_time' => $list_v['purchase_time'],
                        'business_type' => '4',
                        'customer_id'   => $list_v['customers_id'],
                        'goods_id'      => $goods['id'],
                        'goods_code'    => $list_v['goods_code'],
                        'attribute_id'  => (float)$list_v['goods_attr'],
                        'goods_unit'    => (float)$list_v['goods_unit'],
                        'stores_id'     => (float)$list_v['stores_id'],
                        'remark'        => $list_v['remark'],
                        'out_number'    => (float)$list_v['number'],
                        'out_basics'    => (float)$list_v['basic_nmber'],
                        'out_unit'      => $balance_unit,
                        'out_cost'      => $balance_cost,
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ]);
                }
                //收发详情结束
            }
            foreach ($editstock as $editstock_k=>$editstock_v){
                if($editstock_v['stock']<0){
                    $store = Db::name('kuerp_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>$goods['goods_name'].'库存不足,操作失败'];
                    }
                    $this->error($store.'库存不足,操作失败');
                }
            }

            $order_count = [];
            $code_id = Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->column('order_id');
            $purchase_order_info = Db::name('kuerp_goods_sales_order_info')
                ->field('id,purchase_code')
                ->where(['id'=>['in',$code_id]])
                ->select();
            foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
                $purord_info = Db::name('kuerp_goods_saleord_info')
                    ->where(['order_id'=>$purchase_order_info_v['id'],'purchase_id'=>['in',$purchase_info]])->field('sum(number) as number,sum(money) as money,sum(all_money) as all_money')->find();
                $purchase_order_info[$purchase_order_info_k]['pay_count'] = isset($purord_info['number'])?$purord_info['number']:0;
                $purchase_order_info[$purchase_order_info_k]['pay_money'] = isset($purord_info['money'])?$purord_info['money']:0;
                $purchase_order_info[$purchase_order_info_k]['all_money'] = isset($purord_info['all_money'])?$purord_info['all_money']:0;
            }
            foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
                $status = false;
                foreach ($order_count as $order_count_k=>$order_count_v){
                    if($order_count_v['purchase_code']==$purchase_order_info_v['purchase_code']){
                        $order_count[$order_count_k]['store_number'] += $purchase_order_info_v['pay_count'];
                        $status = true;
                    }
                }
                if(!$status){
                    $order_count[] = [
                        'purchase_code'  => $purchase_order_info_v['purchase_code'],
                        'store_number'  => $purchase_order_info_v['pay_count'],
                    ];
                }
            }
            //修改状态
            if(!empty($order_count)){
                foreach ($order_count as $order_count_k=>$order_count_v){
                    $number = Db::name('kuerp_goods_sales_order')->where(['purchase_code'=>$order_count_v['purchase_code']])->field('id,number,store_number')->find();
                    if(($number['number']-$number['store_number'])<=$order_count_v['store_number']){
                        $order_count[$order_count_k]['status'] = 1;
                    }else{
                        $order_count[$order_count_k]['status'] = 2;
                    }
                    $order_count[$order_count_k]['id'] = $number['id'];
                }
            }

            //批次库存数据
            //获取设置
            $set= \think\Db::name('kuerp_sets')->field('type,name,value,is_checked,set')->select();
            $setList = [];
            foreach ($set as $set_k=>$set_v){
                if(!empty($set_v['set'])){
                    $set_v['set'] = unserialize($set_v['set']);
                }
                $setList[$set_v['name']] = $set_v;
            }
            //数量价格格式化
            $number_decimal = $setList['number_decimal']['value'];
            $goods_serial = Db::name('kuerp_goods_sales_info')->where(['id'=>['in',$purchase_info_id]])->select();

            $goods_batch_add = [];$goods_batch_edit = [];$goods_batch_log = [];
            foreach ($goods_serial as $k=>$v){
                $goods = Db::name('kuerp_goods')->where((new Goods())->setWhere(['goods_code'=>$v['goods_code']]))->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
                if($goods['batch']==1){
                    //先通过单位计算需修改多单位商品的库存数量
                    if($goods['unit_id']==$v['goods_unit']){
                        $stock_number = $v['number'];
                    }else{
                        $unit_conversion = Db::name('kuerp_unit_conversion')->where((new Goods())->setWhere(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']]))->value('advance_rate');
                        if(empty($unit_conversion)){
                            if($examine_set!=1){
                                return ['status'=>0,'msg'=>'商品单位信息查询失败'];
                            }
                            $this->error('商品单位信息查询失败');
                        }else{
                            $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                        }
                    }

                    $where = [];
                    $where['goods_id'] = $goods['id'];
                    if($v['goods_attr']){
                        $where['attribute_id'] = $v['goods_attr'];
                    }
                    $where['stores_id'] = $v['stores_id'];
                    $where['batch_id'] = $v['batch_id'];
                    $where = (new Goods())->setWhere($where);
                    $goods_batch_stock = Db::name('kuerp_goods_batch_stock')->where($where)->find();
                    if(empty($goods_batch_stock)){
                        $status = false;
                        foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                            if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$v['goods_id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                                $goods_batch_add[$goods_batch_add_k]['stock'] -= $stock_number;
                                $status = true;
                            }
                        }
                        if(!$status){
                            $goods_batch_add[] = (new Goods())->setDataInfo([
                                'batch_id' => $v['batch_id'],
                                'goods_id' => $goods['id'],
                                'goods_code' => $v['goods_code'],
                                'attribute_id' => $v['goods_attr'],
                                'stores_id' => $v['stores_id'],
                                'stock' => $stock_number,
                                'createtime' => time(),
                                'updatetime' => time(),
                            ]);
                        }
                    }else{
                        if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                            $goods_batch_edit[$goods_batch_stock['id']] -= $stock_number;
                        }else{
                            $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']-$stock_number;
                        }
                    }
                    foreach ($goods_batch_edit as $k2=>$v2){
                        if($v2<0){
                            if($examine_set!=1){
                                return ['status'=>0,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
                            }
                            $this->error('商品'.$goods['goods_name'].'库存不足');
                        }
                    }

                    //商品批次跟踪
                    $goods_batch_log[] = (new Goods())->setDataInfo([
                        'goods_id'      => $goods['id'],
                        'goods_unit'    => $v['goods_unit'],
                        'stores_id'     => $v['stores_id'],
                        'batch_id'      => (float)$v['batch_id'],
                        'number'        => (float)$v['number'],
                        'purchase_code' => $v['purchase_code'],
                        'purchase_time' => $v['purchase_time'],
                        'business_type' => '4',
                        'remarks'       => $v['remark'],
                        'order_id'      => $v['id'],
                        'unit_price'    => $v['unit_price'],
                        'tax_included'  => $v['tax_included'],
                        'all_money'     => $v['all_money'],
                        'tax_money'     => $v['tax_money'],
                        'money_tax_price' => $v['money_tax_price'],
                        'customer_id'   => $v['customers_id'],
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ]);
                }
                //商品批次跟踪结束
            }
            //批次库存数据结束

            //应收账款明细表
            $ex_list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0','arrears'=>['>','0']])->select();
            $accounts_receivable = [];
            foreach ($ex_list as $ex_list_k=>$ex_list_v){
                $accounts_receivable[] = (new Goods())->setDataInfo([
                    'customers_id'      => $ex_list_v['customers_id'],
                    'purchase_time'     => $ex_list_v['purchase_time'],
                    'purchase_code'     => $ex_list_v['purchase_code'],
                    'business_type'     => '6',
                    'receivable'        => $ex_list_v['arrears'],
                    'staff_member_id'   => $ex_list_v['sale_user'],
                    'sale_user_name'    => $ex_list_v['sale_user_name'] ?? '',
                    'remark'            => $ex_list_v['note'],
                    'sale_money'        => $ex_list_v['money_tax_price'],
                    'receivable_money'  => round(($ex_list_v['real_money']+$ex_list_v['customers_money']),4),
                    'amount'            => $ex_list_v['preferential_money'],
                    'cost'              => $ex_list_v['customers_money'],
                    'real_money'        => $ex_list_v['pay_money'],
                    'createtime'        => time(),
                    'updatetime'        => time(),
                ]);
            }

            $admin = Session::get('admin');

            //采购销售费用
            $cost_data = [];
            foreach ($list as $list_k=>$list_v){
                if(!empty($list_v['cost_data'])){
                    $cost_datas = unserialize($list_v['cost_data']);
                    foreach ($cost_datas as $cost_datas_k=>$cost_datas_v){
                        $list_v['supplyer_code'] = isset($list_v['supplyer_code'])?$list_v['supplyer_code']:'';
                        $cost_data[] = (new Goods())->setDataInfo([
                            'purchase_time'     => time(),
                            'purchase_code'     => (new Goods())->getCodes('',27),
                            'business_type'     => '2',
                            'suppliers_ids'     => isset($list_v['customers_id'])?$list_v['customers_id']:null,
                            'suppliers_id'      => $cost_datas_v['suppliers_id'],
                            'expend_type_id'    => $cost_datas_v['expend_type_id'],
                            'purchase_number'   => $list_v['purchase_code'],
                            'purchase_times'    => $list_v['purchase_time'],
                            'money'             => $cost_datas_v['money'],
                            'pay_money'         => $cost_datas_v['money'],
                            'remark'            => $cost_datas_v['remark'],
                            'preparation_id'    => $admin['id'],
                            'operation_id'      => $admin['id'],
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ]);
                    }
                }
            }

            //销售利润表
            $profit = [];
            foreach ($list as $list_k=>$list_v){
                $amount = null;
                $amounts = Db::name('kuerp_goods_sales_info')->where((new Goods())->setWhere(['purchase_code'=>$list_v['purchase_code']]))->sum('dis_money');
                if($amounts>0){
                    $amount = $amounts;
                }
                $profit[] = (new Goods())->setDataInfo([
                    'purchase_type' => '1',
                    'purchase_code' => $list_v['purchase_code'],
                    'purchase_time' => $list_v['purchase_time'],
                    'customers_id'  => $list_v['customers_id'],
                    'sale_user'     => $list_v['sale_user'],
                    'sale_user_name'=> $list_v['sale_user_name'] ?? '',
                    'preparation_id'=> $list_v['preparation_id'],
                    'examine_id'    => $admin['id'],
                    'number'        => $list_v['number'],
                    'amount'        => $amount,
                    'all_money'     => $list_v['all_money'],
                    'tax_money'     => $list_v['tax_money'],
                    'money_tax_price'=> $list_v['money_tax_price'],
                    'preferential_money'=> $list_v['preferential_money'],
                    'purchase_money'=> $list_v['purchase_money'],
                    'real_money'    => $list_v['real_money'],
                    'customers_money'=> $list_v['customers_money'],
                    'need_money'    => $list_v['real_money']+$list_v['customers_money'],
                    'pay_money'     => $list_v['pay_money'],
                    'remark'        => $list_v['note'],
                ]);
            }

            //核销单源单
            $writeoff_source = [];
            foreach ($list as $list_k=>$list_v){
                if($list_v['arrears']>0){
                    $writeoff_source[] = [
                        'purchase_type' => 3,
                        'type' => 1,
                        'customers_id' => $list_v['customers_id'],
                        'purchase_code' => $list_v['purchase_code'],
                        'purchase_time' => $list_v['purchase_time'],
                        'price' => $list_v['real_money'],
                        'money' => $list_v['pay_money'],
                        'write_off' => $list_v['arrears'],
                        'remark' => $list_v['note'],
                    ];
                }
            }

            Db::startTrans();
            try {
                if(!empty($writeoff_source)){
                    Db::name('kuerp_writeoff_source')->insertAll($writeoff_source);
                }
                
                if(!empty($profit)){
                    Db::name('kuerp_goods_sales_profit')->insertAll($profit);
                }
                if(!empty($cost_data)){
                    Db::name('kuerp_cost')->insertAll($cost_data);
                }
                if(!empty($accounts_receivable)){
                    Db::name('kuerp_accounts_receivable')->insertAll($accounts_receivable);
                }

                //序列号跟踪
                if(!empty($serial_log)){
                    Db::name('kuerp_goods_serial_log')->insertAll($serial_log);
                }
                if(!empty($goods_stock_log)){
                    Db::name('kuerp_goods_log')->insertAll($goods_stock_log);
                }
                //批次库存数据
                if(!empty($goods_batch_log)){
                    Db::name('kuerp_goods_batch_log')->insertAll($goods_batch_log);
                }
                if(!empty($goods_batch_add)){
                    foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                        $where = [];
                        $where['goods_code'] = $goods_batch_add_v['goods_code'];
                        $where['stores_id'] = $goods_batch_add_v['stores_id'];
                        $where['batch_id'] = $goods_batch_add_v['batch_id'];
                        if($goods_batch_add_v['attribute_id']>0){
                            $where['attribute_id'] = $goods_batch_add_v['attribute_id'];
                        }
                        $stock = Db::name('kuerp_goods_batch_stock')->where($where)->find();
                        if($stock){
                            Db::name('kuerp_goods_batch_stock')->where(['id'=>$stock['id']])->inc('stock',$goods_batch_add_v['stock'])->update();
                        }else{
                            Db::name('kuerp_goods_batch_stock')->insert($goods_batch_add_v);
                        }
                    }
                }
                if(!empty($goods_batch_edit)){
                    foreach ($goods_batch_edit as $k=>$v){
                        Db::name('kuerp_goods_batch_stock')->where((new Goods())->setWhere(['id'=>$k]))->update(['stock'=>$v]);
                    }
                }
                //批次库存数据结束

                if(!empty($purchase_info_id)){
                    Db::name('kuerp_goods_serial')->where(['sale_id'=>['in',$purchase_info_id]])->update(['store_status'=>'2']);
                    Db::name('kuerp_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_info_id]])->update(['status'=>'1']);
                }
                if(!empty($order_count)){
                    $goodsSalesOrder = (new \app\admin\model\kuerp\GoodsSalesOrder());
                    foreach ($order_count as $order_count_k=>$order_count_v){
                        $goodsSalesOrder->where(['id'=>$order_count_v['id']])->inc('store_number',$order_count_v['store_number'])->update();
                        unset($order_count[$order_count_k]['store_number']);
                    }
                    $goodsSalesOrder->saveAll($order_count);
                }
                if(!empty($payment_log)){
                    (new \app\admin\model\kuerp\SalesPaymentLog())->saveAll($payment_log);
                }
                if(!empty($invoicing)){
                    (new \app\admin\model\kuerp\SalesInvoicing())->saveAll($invoicing);
                }
                $result = $this->model->where(['id'=>['in',$ids],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$admin['id'],'examine_time'=>time(),'operation_id'=>$admin['id']]);
                if(!empty($log)){
                    Db::name('kuerp_accounts_log')->insertAll($log);
                }
                if(!empty($editstock)){
                    (new \app\admin\model\kuerp\GoodsStock())->saveAll($editstock);
                }
                if(!empty($goods_stock)){
                    (new \app\admin\model\kuerp\Goods())->saveAll($goods_stock);
                }
                if(!empty($arrears)){
                    (new \app\admin\model\kuerp\Customers())->saveAll($arrears);
                }
                Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->update(['status'=>'1','times'=>time()]);
                foreach ($info_list as $info_list_k=>$info_list_v){
                    if(isset($info_list_v['id'])){
                        unset($info_list[$info_list_k]['id']);
                    }
                }
                Db::name('kuerp_goods_sales_summary')->insertAll($info_list);
                if(!empty($accountData)){
                    foreach ($accountData as $accountData_k=>$accountData_v){
                        Db::name('kuerp_accounts')->where(['id'=>$accountData_v['account']])->inc('balance',$accountData_v['balance'])->update();
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                if($examine_set!=1){
                    return ['status'=>1,'msg'=>'操作成功'];
                }
                $this->success(sizeof($list).'条数据审核成功');
            }else{
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>'操作失败'];
                }
                $this->error('审核失败');
            }
        }else{
            $plist = $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])->select();
            if(empty($list)){
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>'操作失败'];
                }
                $this->error('请选择需要反审核的数据');
            }
            foreach ($list as $list_k=>$list_v){
                $purchase_id = Db::name('kuerp_goods_saleexc')->where(['purchase_id'=>$list_v['id'],'type'=>'2'])->column('exchange_id');
                if(!empty($purchase_id)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>'不能操作已生成退货单的数据'];
                    }
                    $this->error('不能反审核已生成退货单的数据');
                }
                $purchase_id = Db::name('kuerp_collection_sale')->where(['purchase_number'=>$list_v['purchase_code']])->find();
                if(!empty($purchase_id)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>'不能操作已生成收款单的数据'];
                    }
                    $this->error('不能反审核已生成收款单的数据');
                }
                $purchase_id = Db::name('kuerp_writeoff_info')->where(['purchase_number'=>$list_v['purchase_code']])->find();
                if(!empty($purchase_id)){
                    if($examine_set!=1){
                        return ['status'=>0,'msg'=>'不能操作已生成核销单的数据'];
                    }
                    $this->error('不能反审核已生成核销单的数据');
                }
            }
            $arrears = [];
            foreach ($list as $list_k=>$list_v){
                if($list_v['arrears']>0){
                    $suppliers = Db::name('kuerp_customers')->where(['id'=>$list_v['customers_id']])->field('id,need_receive_account')->find();
                    if($suppliers){
                        $status = false;
                        foreach ($arrears as $arrears_k=>$arrears_v){
                            if($arrears_v['id']==$suppliers['id']){
                                $arrears[$arrears_k]['need_receive_account'] = $arrears_v['need_receive_account']-$list_v['arrears'];
                                $status = true;
                            }
                        }
                        if(!$status){
                            $arrears[] = [
                                'id'  => $suppliers['id'],
                                'need_receive_account'  => $suppliers['need_receive_account']-$list_v['arrears'],
                            ];
                        }
                    }
                }
            }
            $list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])->column('purchase_code');

            $account_list_obj = Db::name('kuerp_accounts')->field('id,account_coding,account_name,balance')->select();
            $account_list = [];
            foreach ($account_list_obj as $account_list_obj_k=>$account_list_obj_v){
                $account_list[$account_list_obj_v['id']] = $account_list_obj_v;
            }

            $log = Db::name('kuerp_accounts_log')->where(['bill_code'=>['in',$list],'business_type'=>'5'])->select();
            $accountData = [];
            foreach ($log as $list_k=>$list_v){
                $accountData[] = [
                    'balance'  => $list_v['income'],
                    'account'  => $list_v['account_coding'],
                ];
            }

            $editstock = [];$goods_stock = [];
            $info_list = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>['in',$list]])->select();

            $purchase_info_id = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>['in',$list]])->column('id');

            $purchase_info = [];
            foreach ($info_list as $list_k=>$list_v){
                $info_list[$list_k]['createtime']        = time();
                $info_list[$list_k]['updatetime']        = time();
                $stock_number = $list_v['basic_nmber'];
                $goods = Db::name('kuerp_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,goods_name,serial')->find();
                if($goods['serial']==1){
                    $serial_count = Db::name('kuerp_goods_serial')->where((new Goods())->setWhere(['sale_id'=>$list_v['id']]))->count();
                    $stock_number = $serial_count;
                }
                $status = false;
                foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                    if($goods_stock_v['id']==$goods['id']){
                        $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']+$stock_number;
                        $status = true;
                    }
                }
                if(!$status){
                    $goods_stock[] = [
                        'id'=>$goods['id'],
                        'inventory'=>$goods['inventory']+$stock_number,
                    ];
                }
                //商品库存
                $where = [];
                $where['goods_code'] = $list_v['goods_code'];
                $where['stores_id'] = $list_v['stores_id'];
                if($list_v['goods_attr']>0){
                    $goods_attr = $list_v['goods_attr'];
                    if($goods_attr>0){
                        $where['attribute_id'] = $goods_attr;
                    }
                }
                $stock = Db::name('kuerp_goods_stock')->where($where)->field('stock,id')->find();
                if($stock){
                    $status = false;
                    foreach ($editstock as $editstock_k=>$editstock_v){
                        if($editstock_v['id']==$stock['id']){
                            $editstock[$editstock_k]['stock'] += $stock_number;
                            $status = true;
                        }
                    }
                    if(!$status){
                        $editstock[] = [
                            'id'=>$stock['id'],
                            'stock'=>(round($stock['stock']+$stock_number,2))
                        ];
                    }
                }
                // else{
                //     if($examine_set!=1){
                //         return ['status'=>0,'msg'=>'系统数据错误，操作失败'];
                //     }
                //     $this->error('系统数据错误,反审核失败');
                // }
                $purchase_info[] = $list_v['id'];
            }

            $order_count = [];
            $code_id = Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->column('order_id');
            $purchase_order_info = Db::name('kuerp_goods_sales_order_info')
                ->field('id,purchase_code')
                ->where(['id'=>['in',$code_id]])
                ->select();
            foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
                $purord_info = Db::name('kuerp_goods_saleord_info')
                    ->where(['order_id'=>$purchase_order_info_v['id'],'purchase_id'=>['in',$purchase_info]])->field('sum(number) as number,sum(money) as money,sum(all_money) as all_money')->find();
                $purchase_order_info[$purchase_order_info_k]['pay_count'] = isset($purord_info['number'])?$purord_info['number']:0;
                $purchase_order_info[$purchase_order_info_k]['pay_money'] = isset($purord_info['money'])?$purord_info['money']:0;
                $purchase_order_info[$purchase_order_info_k]['all_money'] = isset($purord_info['all_money'])?$purord_info['all_money']:0;
            }
            foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
                $status = false;
                foreach ($order_count as $order_count_k=>$order_count_v){
                    if($order_count_v['purchase_code']==$purchase_order_info_v['purchase_code']){
                        $order_count[$order_count_k]['store_number'] += $purchase_order_info_v['pay_count'];
                        $status = true;
                    }
                }
                if(!$status){
                    $order_count[] = [
                        'purchase_code'  => $purchase_order_info_v['purchase_code'],
                        'store_number'  => $purchase_order_info_v['pay_count'],
                    ];
                }
            }
            //修改状态
            if(!empty($order_count)){
                foreach ($order_count as $order_count_k=>$order_count_v){
                    $number = Db::name('kuerp_goods_sales_order')->where(['purchase_code'=>$order_count_v['purchase_code']])->field('id,number,store_number')->find();
                    if($number['store_number']<=$order_count_v['store_number']){
                        $order_count[$order_count_k]['status'] = 0;
                    }else{
                        $order_count[$order_count_k]['status'] = 2;
                    }
                    $order_count[$order_count_k]['id'] = $number['id'];
                }
            }

            //批次库存数据
            //获取设置
            $set= \think\Db::name('kuerp_sets')->field('type,name,value,is_checked,set')->select();
            $setList = [];
            foreach ($set as $set_k=>$set_v){
                if(!empty($set_v['set'])){
                    $set_v['set'] = unserialize($set_v['set']);
                }
                $setList[$set_v['name']] = $set_v;
            }
            //数量价格格式化
            $number_decimal = $setList['number_decimal']['value'];
            $goods_serial = Db::name('kuerp_goods_sales_info')->where(['id'=>['in',$purchase_info_id]])->select();

            $goods_batch_add = [];$goods_batch_edit = [];
            foreach ($goods_serial as $k=>$v){
                $goods = Db::name('kuerp_goods')->where((new Goods())->setWhere(['goods_code'=>$v['goods_code']]))->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
                if($goods['batch']==1){
                    //先通过单位计算需修改多单位商品的库存数量
                    if($goods['unit_id']==$v['goods_unit']){
                        $stock_number = $v['number'];
                    }else{
                        $unit_conversion = Db::name('kuerp_unit_conversion')->where((new Goods())->setWhere(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']]))->value('advance_rate');
                        if(empty($unit_conversion)){
                            if($examine_set!=1){
                                return ['status'=>0,'msg'=>'商品单位信息查询失败'];
                            }
                            $this->error('商品单位信息查询失败');
                        }else{
                            $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                        }
                    }

                    $where = [];
                    $where['goods_id'] = $goods['id'];
                    if($v['goods_attr']){
                        $where['attribute_id'] = $v['goods_attr'];
                    }
                    $where['stores_id'] = $v['stores_id'];
                    $where['batch_id'] = $v['batch_id'];
                    $where = (new Goods())->setWhere($where);
                    $goods_batch_stock = Db::name('kuerp_goods_batch_stock')->where($where)->find();
                    if(empty($goods_batch_stock)){
                        $status = false;
                        foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                            if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$goods['id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                                $goods_batch_add[$goods_batch_add_k]['stock'] += $stock_number;
                                $status = true;
                            }
                        }
                        if(!$status){
                            $goods_batch_add[] = (new Goods())->setDataInfo([
                                'batch_id' => $v['batch_id'],
                                'goods_id' => $goods['id'],
                                'goods_code' => $v['goods_code'],
                                'attribute_id' => $v['goods_attr'],
                                'stores_id' => $v['stores_id'],
                                'stock' => $stock_number,
                                'createtime' => time(),
                                'updatetime' => time(),
                            ]);
                        }
                    }else{
                        if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                            $goods_batch_edit[$goods_batch_stock['id']] += $stock_number;
                        }else{
                            $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']+$stock_number;
                        }
                    }
                }
            }
            //批次库存数据结束

            //应收账款明细表
            $ex_list = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])->column('purchase_code');

            $admin = Session::get('admin');
            Db::startTrans();
            try {
                //销售利润表
                Db::name('kuerp_writeoff_source')->where(['purchase_code'=>['in',$list],'purchase_type'=>'3','type'=>'1'])->delete();

                foreach ($plist as $plist_k=>$plist_v){
                    Db::name('kuerp_goods_sales_profit')->where((new Goods())->setWhere(['purchase_type'=>'1','purchase_code'=>$plist_v['purchase_code']]))->delete();
                }
                Db::name('kuerp_cost')->where((new Goods())->setWhere(['business_type'=>'2','purchase_number'=>['in',$ex_list]]))->delete();
                Db::name('kuerp_accounts_receivable')->where((new Goods())->setWhere(['business_type'=>'6','purchase_code'=>['in',$ex_list]]))->delete();

                //序列号跟踪
                if(!empty($purchase_info_id)){
                    Db::name('kuerp_goods_serial_log')->where((new Goods())->setWhere(['business_type'=>'4','purchase_id'=>['in',$purchase_info_id]]))->delete();
                }
                //收发详情
                if(!empty($purchase_info_id)){
                    Db::name('kuerp_goods_log')->where((new Goods())->setWhere(['business_type'=>'4','purchase_id'=>['in',$purchase_info_id]]))->delete();
                }
                //批次库存数据
                //删除批次跟踪
                if(!empty($purchase_info_id)){
                    Db::name('kuerp_goods_batch_log')->where((new Goods())->setWhere(['business_type'=>'4','order_id'=>['in',$purchase_info_id]]))->delete();
                }
                if(!empty($goods_batch_edit)){
                    foreach ($goods_batch_edit as $k=>$v){
                        Db::name('kuerp_goods_batch_stock')->where((new Goods())->setWhere(['id'=>$k]))->update(['stock'=>$v]);
                    }
                }
                //批次库存数据结束

                if(!empty($purchase_info_id)){
                    Db::name('kuerp_goods_serial')->where(['sale_id'=>['in',$purchase_info_id]])->update(['store_status'=>'1']);
                    Db::name('kuerp_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_info_id]])->update(['status'=>'0']);
                }
                if(!empty($order_count)){
                    $goodsSalesOrder = (new \app\admin\model\kuerp\GoodsSalesOrder());
                    foreach ($order_count as $order_count_k=>$order_count_v){
                        $goodsSalesOrder->where(['id'=>$order_count_v['id']])->dec('store_number',$order_count_v['store_number'])->update();
                        unset($order_count[$order_count_k]['store_number']);
                    }
                    $goodsSalesOrder->saveAll($order_count);
                }
                (new \app\admin\model\kuerp\SalesPaymentLog())->where(['bill_codes'=>['in',$list]])->delete();
                (new \app\admin\model\kuerp\SalesInvoicing())->where(['bill_codes'=>['in',$list]])->delete();

                $result = $this->model->where(['id'=>['in',$ids],'examine_status'=>'1'])->update(['examine_status'=>0,'examine_id'=>0,'examine_time'=>'','operation_id'=>$admin['id']]);
                Db::name('kuerp_accounts_log')->where(['bill_code'=>['in',$list],'business_type'=>5])->delete();
                Db::name('kuerp_goods_sales_summary')->where(['purchase_code'=>['in',$list]])->delete();
                if(!empty($accountData)){
                    foreach ($accountData as $accountData_k=>$accountData_v){
                        Db::name('kuerp_accounts')->where(['account_coding'=>$accountData_v['account']])->dec('balance',$accountData_v['balance'])->update();
                    }
                }
                if(!empty($editstock)){
                    (new \app\admin\model\kuerp\GoodsStock())->saveAll($editstock);
                }
                if(!empty($goods_stock)){
                    (new \app\admin\model\kuerp\Goods())->saveAll($goods_stock);
                }
                if(!empty($arrears)){
                    (new \app\admin\model\kuerp\Customers())->saveAll($arrears);
                }
                Db::name('kuerp_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->update(['status'=>'0']);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if(isset($result) && $result !== false){
                if($examine_set!=1){
                    return ['status'=>1,'msg'=>'操作成功'];
                }
                $this->success(sizeof($list).'条数据反审核成功');
            }else{
                if($examine_set!=1){
                    return ['status'=>0,'msg'=>'操作失败'];
                }
                $this->error('反审核失败');
            }
        }
    }

    //检测可生成退货单
    public function checkPurchase(){
        $order_id = isset($_POST['exchange'])?trim($_POST['exchange']):0;
        if(empty($order_id)){
            $this->error('参数错误');
        }
        $row = Db::name('kuerp_goods_sales')->where(['id'=>$order_id])
            ->field('examine_status,purchase_code')
            ->find();
        if(empty($row)){
            $this->error('参数错误');
        }
        if($row['examine_status']!=1){
            $this->error('此购货单未审核，不可生成退货单');
        }
        $purchase_info = Db::name('kuerp_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->select();
        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
            $purord_info = Db::name('kuerp_goods_saleexc_info')->where(['purchase_id'=>$purchase_info_v['id'],'type'=>'2'])->field('sum(number) as number,sum(money) as money')->select();
            $gp_number = isset($purord_info[0]['number'])?$purord_info[0]['number']:0;
            if($purchase_info_v['number']-$gp_number<=0){
                unset($purchase_info[$purchase_info_k]);
            }
        }
        if(empty($purchase_info)){
            $this->error('此销货单已全部生成退货单');
        }
        $this->success();
    }
    //获取应付款余额
    public function getSuppliers($customers_id){
        if(empty($customers_id)){
            return 0;
        }else{
            $give_account = Db::name('kuerp_customers')->where(['id'=>$customers_id])->value('need_receive_account');
            return (float)$give_account;
        }
    }
    //获取单位信息
    public function getUnits($goods_code='',$store=''){
        if($goods_code){
            $row = Db::name('kuerp_goods')->where(['goods_code'=>$goods_code])->field('id,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,warehousing,warehouse')->find();
            $goods_id = isset($row['id'])?$row['id']:0;
        }else{
            $goods_id = $_POST['goods_id'];
            $row = Db::name('kuerp_goods')->where(['id'=>$goods_id])->field('unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,warehousing,warehouse')->find();
        }
        if(empty($row)){
            return [];
        }
        if($store){
            $stock = Db::name('kuerp_goods_stock')->where(['goods_code'=>$row['goods_code'],'stores_id'=>$store])->value('stock');
        }else{
            $stock = Db::name('kuerp_goods_stock')->where(['goods_code'=>$row['goods_code'],'stores_id'=>$row['manager_warehouse_id']])->value('stock');
        }
        if($row['more_unit']==1){
            $unit_ids_arr = Db::name('kuerp_unit_conversion')->where(['id'=>$row['more_unit_id']])->field('main_unit,vice_unit,advance_rate')->find();
            $unit_ids = [$unit_ids_arr['main_unit'],$unit_ids_arr['vice_unit']];
            $goods_price = Db::name('kuerp_goods_price')->where(['unit'=>['in',$unit_ids],'goods_id'=>$goods_id])->select();
        }else{
            $unit_ids = [$row['unit_id']];
        }
        $unit = Db::name('kuerp_unit')->where(['id'=>['in',$unit_ids]])->field('id,name')->select();
        foreach ($unit as $unit_k=>$unit_v){
            if(isset($goods_price)){
                foreach ($goods_price as $goods_price_k=>$goods_price_v){
                    if($unit_v['id']==$goods_price_v['unit']){
                        $unit[$unit_k]['is_default'] = $goods_price_v['is_default'];
                        if($unit_v['id']==$unit_ids_arr['vice_unit']){
                            $unit[$unit_k]['purchase'] = round(($goods_price_v['purchase']/$unit_ids_arr['advance_rate']),2);
                            $unit[$unit_k]['basic_nmber'] = $unit_ids_arr['advance_rate'];
                        }else{
                            $unit[$unit_k]['purchase'] = $goods_price_v['purchase'];
                            $unit[$unit_k]['basic_nmber'] = 1;
                        }
                    }
                }
            }else{
                if($unit_v['id']==$row['unit_id']){
                    $unit[$unit_k]['is_default'] = 1;
                    $unit[$unit_k]['basic_nmber'] = 1;
                    $unit[$unit_k]['purchase'] = $row['purchase'];
                }
            }
        }
        $data = [];
        foreach ($unit_ids as $unit_ids_k=>$unit_ids_v){
            foreach ($unit as $unit_k=>$unit_v){
                if($unit_ids_v==$unit_v['id']){
                    if($unit_v['is_default']==1){
                        $unit_v['stock'] = is_null($stock)?0:$stock;
                    }else{
                        $unit_v['stock'] = round($stock/$unit_v['basic_nmber'],2);
                    }
                    $data[] = $unit_v;
                }
            }
        }
        return json_encode($data);
    }

    //获取单位价格信息
    public function getUnit($goods_code='',$store='',$attr='',$customers_id=''){
        $taxes= Db::name('kuerp_sets')->where(['name'=>'price_taxes'])->value('is_checked');

        if($goods_code){
            $row = Db::name('kuerp_goods')->where(['goods_code'=>$goods_code])
                ->field('market_sell_price,wholesale_price,vip_price,discount,discount2,batch,serial,id,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,batch,shelf_life,warehousing,warehouse')
                ->find();
            $goods_id = isset($row['id'])?$row['id']:0;
        }else{
            $goods_id = isset($_POST['goods_id'])?$_POST['goods_id']:0;
            $row = Db::name('kuerp_goods')->where(['id'=>$goods_id])
                ->field('market_sell_price,wholesale_price,vip_price,discount,discount2,batch,serial,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,batch,shelf_life,warehousing,warehouse')
                ->find();
        }
        if(empty($row)){
            return [];
        }

        //获取设置
        $set= \think\Db::name('kuerp_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $number_decimal = $setList['number_decimal']['value'];
        $price_decimal  = $setList['price_decimal']['value'];

        $field = 'market_sell_price';
        if($customers_id){
            $customers = Db::name('kuerp_customers')->where(['id'=>$customers_id])->find();
            if($customers){
                switch ($customers['customerlevel_id']){
                    case 1:
                        $field = 'market_sell_price';
                        break;
                    case 2:
                        $field = 'wholesale_price';
                        break;
                    case 3:
                        $field = 'vip_price';
                        break;
                    case 4:
                        $field = 'discount';
                        break;
                    case 5:
                        $field = 'discount2';
                        break;
                    default:
                        break;
                }
            }
        }

        $auxiliary = Db::name('kuerp_auxiliary')->where(['status'=>1])->column('name','id');
        $goods_attr = Db::name('kuerp_goods_attr')->where(['goods_id'=>$goods_id])->select();
        foreach ($goods_attr as $goods_attr_k=>$goods_attr_v){
            $aux_combination = Db::name('kuerp_aux_combination')->where(['id'=>$goods_attr_v['attribute_id']])->value('attr_ids');
            $goods_attr[$goods_attr_k]['attr_ids'] = [];
            $goods_attr[$goods_attr_k]['attr_name'] = '';
            if($aux_combination){
                $goods_attr[$goods_attr_k]['attr_id'] = $aux_combination;
                $aux_combination = explode('&',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_ids'] = $aux_combination;
                foreach ($aux_combination as $aux_combination_k=>$aux_combination_v){
                    $aux_combination[$aux_combination_k] = $auxiliary[$aux_combination_v];
                }
                $aux_combination = implode('/',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_name'] = $aux_combination;
            }
        }


        $where = [];
        $where['goods_id'] = $goods_id;
        if($store){
            $where['stores_id'] = $store;
        }else{
            $where['stores_id'] = $row['manager_warehouse_id'];
        }
        if($attr){
            //$attribute_id = Db::name('kuerp_goods_attr')->where(['goods_id'=>$goods_id,'id'=>$attr])->value('attribute_id');
            $where['attribute_id'] = $attr;
        }
        $stock = Db::name('kuerp_goods_stock')->where($where)->value('stock');
        if($row['more_unit']==1){
            $unit = Db::name('kuerp_unit_conversion')->alias('uc')
                ->join('kuerp_unit u','u.id=uc.vice_unit')
                ->where(['uc.main_unit'=>$row['unit_id']])
                ->order('uc.advance_rate','ASC')
                ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                ->select();
            $unit_ids = [$row['unit_id']];
            foreach ($unit as $unit_k=>$unit_v){
                $unit_ids[] = $unit_v['id'];
            }
            $goods_price = Db::name('kuerp_goods_price')->where(['unit'=>['in',$unit_ids],'goods_id'=>$goods_id])->select();
            foreach ($goods_price as $goods_price_k=>$goods_price_v){
                foreach ($unit as $unit_k=>$unit_v){
                    if($goods_price_v['unit']==$row['unit_id']){
                        $goods_price[$goods_price_k]['advance_rate'] = 1;
                    }else if($goods_price_v['unit']==$unit_v['id']){
                        $goods_price[$goods_price_k]['advance_rate'] = $unit_v['advance_rate'];
                    }
                }
            }
        }else{
            $unit_ids = [$row['unit_id']];
        }

        $unit = Db::name('kuerp_unit')->where(['id'=>['in',$unit_ids]])->field('id,name,classid')->select();
        foreach ($unit as $unit_k=>$unit_v){
            if(isset($goods_price)){
                foreach ($goods_price as $goods_price_k=>$goods_price_v){
                    if($unit_v['id']==$goods_price_v['unit']){
                        $unit[$unit_k]['is_default'] = $goods_price_v['is_default'];
                        if($field=='discount' || $field=='discount2'){
                            $unit[$unit_k]['purchase'] = round( ($goods_price_v['market_sell_price']*$goods_price_v[$field]/100),$price_decimal );
                        }else{
                            $unit[$unit_k]['purchase'] = $goods_price_v[$field];
                        }
                        if($goods_price_v['is_default']!=1){
                            $unit[$unit_k]['basic_nmber'] = $goods_price_v['advance_rate'];
                        }else{
                            $unit[$unit_k]['basic_nmber'] = 1;
                        }
                    }
                }
            }else{
                if($row['auxiliary']==1 && !empty($attr)){
                    $purchase_data = Db::name('kuerp_goods_attr')->where(['goods_id'=>$goods_id,'id'=>$attr])->find();
                    if($field=='discount' || $field=='discount2'){
                        $purchase = round( ($purchase_data['market_sell_price']*$purchase_data[$field]/100),$price_decimal );
                    }else{
                        $purchase = $purchase_data[$field];
                    }
                }else{
                    if($field=='discount' || $field=='discount2'){
                        $purchase = round( ($row['market_sell_price']*$row[$field]/100),$price_decimal );
                    }else{
                        $purchase = $row[$field];
                    }
                }
                if($unit_v['id']==$row['unit_id']){
                    $unit[$unit_k]['is_default'] = 1;
                    $unit[$unit_k]['basic_nmber'] = 1;
                    $unit[$unit_k]['purchase'] = $purchase;
                }
            }
            $unit[$unit_k]['purchase'] = isset($unit[$unit_k]['purchase'])?$unit[$unit_k]['purchase']:0;
            $unit[$unit_k]['basic_nmber'] = isset($unit[$unit_k]['basic_nmber'])?$unit[$unit_k]['basic_nmber']:1;
            $unit[$unit_k]['is_default'] = isset($unit[$unit_k]['is_default'])?$unit[$unit_k]['is_default']:2;
        }

        $set= Db::name('kuerp_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();
        foreach ($unit as $unit_k=>$unit_v){
            $tax = $set['value'];
            if(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1){
                $unit[$unit_k]['tax'] = 1;
                $unit[$unit_k]['tax_rate'] = $tax;
            }else{
                $unit[$unit_k]['tax'] = 0;
                $unit[$unit_k]['tax_rate'] = 0;
            }
            if(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1 && $taxes==1){
                $unit[$unit_k]['purchase'] = round(($unit_v['purchase']/(100+$tax)*100),4);
                $unit[$unit_k]['tax_included'] = round(($unit_v['purchase']),4);
            }elseif(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1 && $taxes!=1){
                $unit[$unit_k]['purchase'] = round(($unit_v['purchase']),4);
                $unit[$unit_k]['tax_included'] = round(($unit_v['purchase']*(100+$tax)/100),4);
            }else{
                $unit[$unit_k]['purchase'] = round(($unit_v['purchase']),4);
                $unit[$unit_k]['tax_included'] = round(($unit_v['purchase']),4);
            }
        }
        $data = [];
        foreach ($unit_ids as $unit_ids_k=>$unit_ids_v){
            foreach ($unit as $unit_k=>$unit_v){
                if($unit_ids_v==$unit_v['id']){
                    if($unit_v['is_default']==1){
                        $unit_v['stock'] = is_null($stock)?0:$stock;
                    }else{
                        $unit_v['stock'] = round($stock/$unit_v['basic_nmber'],2);
                    }
                    $unit_v['tax_money'] = round(($unit_v['tax_included']-$unit_v['purchase']),4);
                    $data[] = $unit_v;
                }
            }
        }
        return json_encode(['unit'=>$data,'attr'=>$goods_attr,'goods'=>$row]);
    }

    public function formatInfo2(){
        $data = input();

        $row = Db::name('kuerp_goods')->where(['goods_code'=>$data['goods_code']])->field('batch,serial,id,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id')->find();
        if(empty($row)){
            return [];
        }else{
            $goods_unit = $data['goods_unit'];
            if($row['more_unit']==1){//多单位，多属性以单位为准
                $goods_price = Db::name('kuerp_goods_price')->where(['goods_code'=>$data['goods_code'],'unit'=>$goods_unit])->find();
            }elseif ($row['more_unit']!=1 && $row['auxiliary']==1){//单一单位，多属性以属性价格为准
                $goods_price = Db::name('kuerp_goods_attr')->where(['id'=>$data['attr']])->find();
            }
        }

        //获取设置
        $set= \think\Db::name('kuerp_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $number_decimal = $setList['number_decimal']['value'];
        $price_decimal  = $setList['price_decimal']['value'];

        //税率
        $taxes= Db::name('kuerp_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();
        if(!isset($data['tax_rate']) || (isset($data['tax_rate']) && $data['tax_rate']==='')){
            $data['tax_rate'] = $taxes['value'];
        }
        $taxes_status = Db::name('kuerp_sets')->where(['name'=>'taxes'])->value('is_checked');//是否启用税金
        if($taxes_status!=1){
            $data['tax_rate'] = 0;
            $data['tax_money'] = 0;
            $data['tax_included'] = $data['unit_price'];
            $data['money_tax_price'] = $data['all_money'];
        }

        //需格式化字段数组
        $format = [
            'number'=>$number_decimal,
            'allow_stock'=>$number_decimal,
            'basic_nmber'=>$number_decimal,
            'unit_price'=>$price_decimal,
            'back_money'=>$price_decimal,//返款金额
            'tax_included'=>$price_decimal,
            'discount'=>$price_decimal,
            'dis_money'=>$price_decimal,
            'all_money'=>$price_decimal,
            'tax_rate'=>$price_decimal,
            'tax_money'=>$price_decimal,
            'money_tax_price'=>$price_decimal,
            'advance_rate'=>$number_decimal,
        ];
        foreach ($data as $k=>$v){
            if(array_key_exists($k,$format)){
                $data[$k] = (float)$data[$k];
            }
        }

        $field = 'market_sell_price';
        $customers_id = isset($data['customers_id'])?$data['customers_id']:'';
        if($customers_id){
            $customers = Db::name('kuerp_customers')->where(['id'=>$customers_id])->find();
            if($customers){
                switch ($customers['customerlevel_id']){
                    case 1:
                        $field = 'market_sell_price';
                        break;
                    case 2:
                        $field = 'wholesale_price';
                        break;
                    case 3:
                        $field = 'vip_price';
                        break;
                    case 4:
                        $field = 'discount';
                        break;
                    case 5:
                        $field = 'discount2';
                        break;
                    default:
                        break;
                }
            }
        }

        $data['tax_included'] = isset($data['tax_included'])?$data['tax_included']:$data['unit_price']*(100+$data['tax_rate'])/100;
        $data['tax_rate'] = isset($data['tax_rate'])?$data['tax_rate']:0;
        $data['discount'] = isset($data['discount'])?$data['discount']:0;
        $data['dis_money'] = isset($data['dis_money'])?$data['dis_money']:0;
        $data['back_money'] = isset($data['back_money'])?$data['back_money']:0;

        $taxes= Db::name('kuerp_sets')->where(['name'=>'price_taxes'])->value('is_checked');//价格含税
        $now_field = $data['now_field'];
        switch ($now_field){
            case 'goods_unit':
                //商品单位
                if($taxes){
                    $data['tax_included'] = isset($goods_price[$field])?$goods_price[$field]:$data['tax_included'];//含税单价
                    $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                }else{
                    $data['unit_price'] = isset($goods_price[$field])?$goods_price[$field]:$data['unit_price'];//单价
                    $data['tax_included'] = $data['unit_price']*(100+$data['tax_rate'])/100;//含税单价
                }
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'attr':
                //商品属性
                if($taxes){
                    $data['tax_included'] = isset($goods_price[$field])?$goods_price[$field]:$data['tax_included'];//含税单价
                    $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                }else{
                    $data['unit_price'] = isset($goods_price[$field])?$goods_price[$field]:$data['unit_price'];//单价
                    $data['tax_included'] = $data['unit_price']*(100+$data['tax_rate'])/100;//含税单价
                }
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'number':
                //数量
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'unit_price':
                //单价
                $data['tax_included'] = $data['unit_price']*(100+$data['tax_rate'])/100;//含税单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'tax_included':
                //含税单价
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'tax_rate':
                //税率
                $data['tax_included'] = $data['unit_price']*(100+$data['tax_rate'])/100;//含税单价
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'tax_money':
                //税额
                $data['money_tax_price'] = $data['all_money'] + $data['tax_money'];//价税合计减折扣额
                break;
            case 'discount':
                //折扣率
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'dis_money':
                //折扣额
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['discount'] = (100*$data['dis_money']+$data['dis_money']*$data['tax_rate'])/$data['money_tax_price'];//折扣率
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'back_money':
                //折扣额
                $data['money_tax_price'] = $data['tax_included']*$data['number'];//价税合计未减折扣额
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                $data['discount'] = (100*$data['dis_money']+$data['dis_money']*$data['tax_rate'])/$data['money_tax_price'];//折扣率
                $data['money_tax_price'] = $data['money_tax_price'] - ($data['money_tax_price'] * ($data['discount'])/100) - $data['back_money'];//价税合计减折扣额
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                break;
            case 'all_money':
                //购货金额
                $data['money_tax_price'] = $data['all_money']*(100+$data['tax_rate'])/100;//价税合计
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                $money_tax_price = $data['money_tax_price']*(100+$data['discount'])/100 + $data['back_money'];//价税合计未减折扣额
                $data['tax_included'] = $money_tax_price/$data['number'];//含税单价
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                break;
            case 'money_tax_price':
                //价税合计
                $data['all_money'] = $data['money_tax_price']*100/(100+$data['tax_rate']);//购货金额
                $data['tax_money'] = $data['all_money']*$data['tax_rate']/100;//税
                $money_tax_price = $data['money_tax_price']*(100+$data['discount'])/100 + $data['back_money'];//价税合计未减折扣额
                $data['tax_included'] = $money_tax_price/$data['number'];//含税单价
                $data['unit_price'] = $data['tax_included']*100/(100+$data['tax_rate']);//单价
                $data['dis_money'] = $data['money_tax_price']/(100+$data['tax_rate'])*$data['discount'];//折扣额
                break;
            default:
                return [];
                break;
        }

        $data['advance_rate'] = 1;
        if($row['more_unit']==1){
            $advance_rate = Db::name('kuerp_unit_conversion')->where(['main_unit'=>$row['more_unit_id'],'vice_unit'=>$goods_price['unit']])->value('advance_rate');
            if(!empty($advance_rate)){
                $data['advance_rate'] = $advance_rate;
            }
        }
        $data['basic_nmber'] = $data['number']*$data['advance_rate'];
        foreach ($data as $data_k=>$data_v){
            if(array_key_exists($data_k,$format)){
                $data[$data_k] = round($data[$data_k],$format[$data_k]);
            }
        }

        if(isset($data['tax_rate'])){
            $data['tax_money'] = $data['money_tax_price']-$data['all_money'];
        }else{
            $data['tax_money'] = 0;
        }

        $arr = [];
        foreach ($data as $data_k=>$data_v){
            if(array_key_exists($data_k,$format)){
                $data[$data_k] = round($data[$data_k],$format[$data_k]);

                if($format[$data_k]>0){
                    $price = explode('.',$data[$data_k]);
                    if(isset($price[1])){
                        $cha = $format[$data_k]-strlen($price[1]);
                    }else{
                        $cha = $format[$data_k];
                        $data[$data_k] = $data[$data_k].'.';
                    }
                    $str = '';
                    for ($a=0;$a<$cha;$a++){
                        $str .= '0';
                    }
                    $data[$data_k] .= $str;
                }

            }
            $arr[] = ['key'=>$data_k,'value'=>$data[$data_k]];
        }
        return json_encode(['data'=>$arr]);
    }
    //获取批次
    public function getBranch($goods_code=''){
        $data = input();
        $row = Db::name('kuerp_goods')->where(['goods_code'=>$goods_code])->field('batch,shelf_life')->find();
        $goods_batch = Db::name('kuerp_goods_batch')->where(['goods_code'=>$data['goods_code']])->field('id,batch_name,manufacture,guarantee,validity')->select();
        foreach ($goods_batch as $goods_batch_k=>$goods_batch_v){
            $goods_batch[$goods_batch_k]['manufacture'] = date('Y-m-d',$goods_batch_v['manufacture']);
            $goods_batch[$goods_batch_k]['validity'] = date('Y-m-d',$goods_batch_v['validity']);
        }
        return json_encode(['goods'=>$row,'batch'=>$goods_batch]);
    }
    public function getTime($manufacture='',$shelf_life='',$validity=''){
        if(!empty($manufacture) && !empty($shelf_life)){
            $validity = date('Y-m-d',strtotime($manufacture)+$shelf_life*86400);
        }elseif(!empty($validity) && !empty($shelf_life)){
            $manufacture = date('Y-m-d',strtotime($validity)-$shelf_life*86400);
        }elseif(!empty($validity) && !empty($manufacture)){
            $shelf_life = ceil((strtotime($validity)-strtotime($manufacture))/86400);
        }
        return json_encode(['manufacture'=>$manufacture,'shelf_life'=>$shelf_life,'validity'=>$validity]);
    }
    //获取客户收货地址
    public function getReceivingAddress(){
        $customers_id = isset($_POST['customers_id'])?trim($_POST['customers_id']):0;
        if(empty($customers_id)){
            return '';
        }
        $customer = Db::name('kuerp_customers')->where(['id'=>$customers_id])->find();
        if ($customer) {
            // $address = $customer['mergename'] ? str_replace(',', '', $customer['mergename']) : '';
            // return $address.$customer['address'];
            return $customer['address'];
        } else {
            return '';
        }
        // $address = Db::name('kuerp_customers')->where(['id'=>$customers_id])->value('getgoods_address');
        // return (empty($address)?'':$address);
    }

    /**
     * 更新客户欠款信息
     * 废弃
     */
    public function test() 
    {
        $list = $this->model->where(['real_money'=>['exp',Db::raw(' > pay_money')],'examine_status'=>'1'])->select();
        dump($list);die;
        $account_list_obj = Db::name('kuerp_accounts')->field('id,account_coding,account_name,balance')->select();
        $account_list = [];
        foreach ($account_list_obj as $account_list_obj_k=>$account_list_obj_v){
            $account_list[$account_list_obj_v['id']] = $account_list_obj_v;
        }
        $arrears = [];
        $log = [];
        $payment_log = [];$invoicing = [];
        $set_discount = \think\Db::name('kuerp_sets')->where(['name'=>'discount'])->value('is_checked');
        //核销单源单
        $writeoff_source = [];
        $sale_update = [];
        foreach ($list as $list_k=>$list_v){
            $examine_ids[] = $list_v['id'];
            $list_v['account'] = 7;
            $list_v['arrears'] = $list_v['real_money']-$list_v['pay_money'];
            $sale_update[] = [
                'id' => $list_v['id'],
                'arrears' => $list_v['arrears'],
                'account' => $list_v['account']
            ];
            if($list_v['arrears']>0){
                $suppliers = Db::name('kuerp_customers')->where(['id'=>$list_v['customers_id']])->field('id,need_receive_account')->find();
                if($suppliers){
                    $status = false;
                    foreach ($arrears as $arrears_k=>$arrears_v){
                        if($arrears_v['id']==$suppliers['id']){
                            $arrears[$arrears_k]['need_receive_account'] = $list_v['arrears']+$arrears_v['need_receive_account'];
                            $status = true;
                        }
                    }
                    if(!$status){
                        $arrears[] = [
                            'id'  => $suppliers['id'],
                            'need_receive_account'  => $list_v['arrears']+$suppliers['need_receive_account'],
                        ];
                    }
                }
            }
            if($list_v['pay_money']>0){
                $accountData[] = [
                    'balance'  => $list_v['pay_money'],
                    'account'  => $list_v['account'],
                ];
                $log[] = [
                    'account_coding'    => $account_list[$list_v['account']]['account_coding'],
                    'account_name'      => $account_list[$list_v['account']]['account_name'],
                    'balance'           => $account_list[$list_v['account']]['balance']-$list_v['pay_money'],
                    'income'            => $list_v['pay_money'],
                    'pay_time'          => $list_v['purchase_time'],
                    'bill_code'         => $list_v['purchase_code'],
                    'business_type'     => 5,
                    'customers_id'      => $list_v['customers_id'],
                    'remark'            => $list_v['note'],
                    'createtime'        => time(),
                    'updatetime'        => time(),
                ];
            }
            $payment_log[] = [
                'customers_id'   => $list_v['customers_id'],
                'sale_user'      => $list_v['sale_user'],
                'sale_user_name' => $list_v['sale_user_name'] ?? '',
                'business_type'  => 1,
                'bill_time'      => $list_v['purchase_time'],
                'bill_code'      => $list_v['purchase_code'],
                'bill_codes'     => $list_v['purchase_code'],
                'purchase_money' => $list_v['all_money'],
                'discount_money' => $list_v['preferential_money'],
                'real_money'     => $list_v['real_money'],
                'money_tax_price'=> $list_v['money_tax_price'],
                'pay_money'      => $list_v['pay_money'],
                'give_money'     => $list_v['arrears'],
                'reamrk'         => $list_v['note'],
                'createtime'     => time(),
            ];
            if($set_discount==1){
                $money = $list_v['real_money'];
            }else{
                $money = $list_v['money_tax_price'];
            }
            $invoicing[] = [
                'customers_id'   => $list_v['customers_id'],
                'status'         => $list_v['pay_status'],
                'bill_time'      => $list_v['purchase_time'],
                'bill_code'      => $list_v['purchase_code'],
                'bill_codes'     => $list_v['purchase_code'],
                'money'          => $list_v['real_money'],
                'tax'            => $list_v['tax_money'],
                'real_money'     => $money,
                'pay_money'      => 0,
                'give_money'     => $money,
                'createtime'     => time(),
            ];
            $accounts_receivable[] = (new Goods())->setDataInfo([
                'customers_id'      => $list_v['customers_id'],
                'purchase_time'     => $list_v['purchase_time'],
                'purchase_code'     => $list_v['purchase_code'],
                'business_type'     => '6',
                'receivable'        => $list_v['arrears'],
                'staff_member_id'   => $list_v['sale_user'],
                'sale_user_name'    => $list_v['sale_user_name'] ?? '',
                'remark'            => $list_v['note'],
                'sale_money'        => $list_v['money_tax_price'],
                'receivable_money'  => round(($list_v['real_money']+$list_v['customers_money']),4),
                'amount'            => $list_v['preferential_money'],
                'cost'              => $list_v['customers_money'],
                'real_money'        => $list_v['pay_money'],
                'createtime'        => time(),
                'updatetime'        => time(),
            ]);
            $writeoff_source[] = [
                'purchase_type' => 3,
                'type' => 1,
                'customers_id' => $list_v['customers_id'],
                'purchase_code' => $list_v['purchase_code'],
                'purchase_time' => $list_v['purchase_time'],
                'price' => $list_v['real_money'],
                'money' => $list_v['pay_money'],
                'write_off' => $list_v['arrears'],
                'remark' => $list_v['note'],
            ];
        }
        Db::startTrans();
        try {
            if(!empty($writeoff_source)){
                Db::name('kuerp_writeoff_source')->insertAll($writeoff_source);
            }
            
            if(!empty($accounts_receivable)){
                Db::name('kuerp_accounts_receivable')->insertAll($accounts_receivable);
            }

            if(!empty($payment_log)){
                (new \app\admin\model\kuerp\SalesPaymentLog())->saveAll($payment_log);
            }
            if(!empty($invoicing)){
                (new \app\admin\model\kuerp\SalesInvoicing())->saveAll($invoicing);
            }
            $result = $this->model->saveAll($sale_update);
            if(!empty($log)){
                Db::name('kuerp_accounts_log')->insertAll($log);
            }
            if(!empty($arrears)){
                (new \app\admin\model\kuerp\Customers())->saveAll($arrears);
            }
            if(!empty($accountData)){
                foreach ($accountData as $accountData_k=>$accountData_v){
                    Db::name('kuerp_accounts')->where(['id'=>$accountData_v['account']])->inc('balance',$accountData_v['balance'])->update();
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        // if(isset($result) && $result !== false){
        //     $this->success(sizeof($list).'条数据审核成功');
        // }else{
        //     $this->error('审核失败');
        // }
        die;
    }

    public function scoreapply($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            if ($this->scoreConfig['consume_get_score'] != 1 || $this->scoreConfig['consume_get_score_ratio'] <= 0) {
                $this->error('积分赠送功能未开启');
            }
            if($row['real_money'] > $row['pay_money']){
                $this->error('全都回款后方可申请赠送积分');
            }
            
            $params = $this->request->post("row/a");
            if ($params) {
                // $money_tax_price = GoodsSalesInfo::where(['purchase_code' =>  $row['purchase_code'], 'goods_code' => ['in',array_merge($this->goods_code_caijia,$this->goods_code_xunjia)]])->sum('money_tax_price');
                // $maxScore = $money_tax_price * $this->scoreConfig['consume_get_score_ratio'] * 0.01;
                // //获取已申请积分
                // $applyedScore = ScoreApply::where(['goodssales_code' => $row['purchase_code'], 'check_status' => ['in', [0, 1, 2]]])->sum('total_score');
                // $apply_data = $params['apply_data'];
                // $total_score = $applyedScore;
                // foreach ($apply_data as $k=>$v){
                //     $total_score += $v['score'];
                // }
                // if ($total_score > $maxScore) {
                //     $this->error('最多可申请'.$maxScore.'积分');
                // }
                
                // $params = $this->preExcludeFields($params);
                $params['goodssales_id'] = $ids;
                $params['goodssales_code'] = $row['purchase_code'];
                Db::startTrans();
                try {
                    $result = (new ScoreApply())->addScoreApply($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('申请成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['no_money'] = $row['real_money'] -$row['pay_money'];
        if($row['no_money'] <= 0){
            $row['no_money'] = 0;
        }
        $row['purchase_time'] = date('Y-m-d', $row['purchase_time']);

        $this->view->assign("ids", $ids);
        $this->view->assign("row", $row);

        $goodsList = GoodsSalesInfo::with(['goods'])->where(['purchase_code'=>$row['purchase_code']])->select();
        $unitids = array_column($goodsList,'goods_unit');
        $goodsunits = Db::name('kuerp_unit')->where('id','in',$unitids)->column('name','id');
        foreach ($goodsList as $key => $row) {
            $row->getRelation('goods')->visible(['goods_name', 'goods_image','id']);
            $goodsList[$key]['serial'] = '';
            if (!empty($row['period'])) {
                $period = unserialize($row['period']);
                foreach ($period as $k1=>$v1) {
                    $goodsList[$key]['serial'] .= $v1['serial'].'-'.$v1['remark'].',';
                }
                $goodsList[$key]['serial'] = rtrim($goodsList[$key]['serial'], ',');
            }
            $goodsList[$key]['goods_unit'] = $goodsunits[$row['goods_unit']] ?? $row['goods_unit'];
        }
        $this->view->assign("goods_list", $goodsList);

        $customer_info = Db::name('kuerp_customers')->where(['id'=>$row['customers_id']])->find();
        $this->view->assign("customer_info", $customer_info);

        //获取申请记录
        $applyList = ScoreApply::with(['admin'])->where(['goodssales_id' => $ids])->order('id desc')->select();
        foreach ($applyList as $key => $row) {
            $row->getRelation('admin')->visible(['nickname']);
            $applyList[$key]['createtime'] = date('Y-m-d', $row['createtime']);
            $applyList[$key]['apply_data'] = json_decode($row['apply_data'], true);
            $applyList[$key]['paystatus_text'] = $row['pay_status'] == 0 ? '待赠送' : '已赠送';
        }
        $this->view->assign("applyList", $applyList);
        return $this->view->fetch();
    }
    
}
